How to format numbers as thousands separators in Dart
Solution 1
You can use NumberFormat passing a custom format in ICU formatting pattern, take a look in NumberFormat.
import 'package:intl/intl.dart';
void main() {
var formatter = NumberFormat('#,##,000');
print(formatter.format(16987));
print(formatter.format(13876));
print(formatter.format(456786));
}
Output
16,987
13,876
4,56,786
Solution 2
I found NumberFormat class from intl package very useful as it provides different ways to format numbers.
By default the NumberFormat class format's number in million's using default American locale and we can format numbers in lakh using Indian locale(It can format number or currency according to any countries locale).NumberFormat.decimalPattern([String locale])
.
import 'package:intl/intl.dart';
void main() {
NumberFormat numberFormat = NumberFormat.decimalPattern('hi');
print(numberFormat.format(16987));
print(numberFormat.format(13876));
print(numberFormat.format(456786));
}
Output
16,987
13,876
4,56,786
Related videos on Youtube
Shubhamhackz
🔭 I’m currently working on few flutter projects 👯 I’m looking to collaborate on open source projects 📝 I regulary write articles on https://medium.com/@shubhamhackzz 💬 Ask me about flutter, dart and open source 🌱 I’m currently learning Node.js and Express 📫 Through me a mail at [email protected] ⚡ Fun fact Google India Scholar 2018 (Android)
Updated on June 04, 2022Comments
-
Shubhamhackz almost 2 years
I have to format numbers as thousands separators in dart. I have numbers like:
16987 13876 456786
and I want to format them as :
16,987 13,876 4,56,786
-
Mano Haran over 3 yearsIs it possible to do the same for string? i am having hard time doing this.
-
Dlani Mendes almost 3 years@ManoHaran Hi! Use
double.tryParse("10000")
ordouble.parse("10000")
, after this just format.