Reputation: 24
Is there a way to format a number :
from 1 to 1.00,
from 2.5 to 2.50,
from 2.1234 to 2.1234
so basically the number will have a minimum of 2 decimal places
Thanks for your help.
Upvotes: 0
Views: 5604
Reputation: 185
A non elegant way using Intl package:
var f = NumberFormat('#.00###############', 'en_Us');
print(f.format(2.123400))
and you will get
2.1234
but if your number have more decimal digit than you have '#' in format string then it's not show. For example
var f = NumberFormat('#.00##', 'en_Us');
print(f.format(2.123456))
you will get
2.1234
I think that way works most of cases. Or you can make format function by yourself. Like this:
String formatNumber(double number) {
int precision = 0;
while ((number * pow(10, precision)) % 10 != 0) {
precision++;
}
return number.toStringAsFixed(max(precision - 1, 2));
}
In this case you don't use Intl package. There is no problem with number of digit after dot. BUT i belive that is a much slower than using intl package.
Upvotes: 2
Reputation: 182
you can use someDoubleValue.toStringAsFixed(2)
what this does is it basically adds or removes floating points from value
Note: if you parse double from this result string again, it will convert back (5.00 => 5)
Example:
String parseNumber(value) {
String strValue = value.toString();
List parsedNumber = strValue.split(".");
String newValue;
if (parsedNumber.length == 1) {
newValue = value.toStringAsFixed(2);
} else {
String decimalPlace = parsedNumber[1];
if (decimalPlace.length > 2) {
newValue = value.toString();
} else {
newValue = value.toStringAsFixed(2);
}
}
return newValue;
}
Upvotes: 0
Reputation: 6357
The Intl package has a set of formatting classes than can help with this use case in particular the NumberFormat Class
Upvotes: 0