0

I want to set a double, let's call it Price, in Dart, so that it always gives me a double of 2 decimal places.

So 2.5 would return 2.50 and 2.50138263 would also return 2.50.

greenzebra
  • 412
  • 1
  • 5
  • 18

2 Answers2

3

The simplest answer would be double's built-in toStringAsFixed.

In your case

double x = 2.5;
print('${x.toStringAsFixed(2)}');
x = 2.50138263;
print('${x.toStringAsFixed(2)}');

Would both return 2.50. Be aware that this truncates (e.g., 2.519 returns 2.51). It does not use the standard rounding (half-even) banker's algorithm.

I recommend using a NumberFormat from the intl package; The parsing and formatting rules are worth learning since they appear in other languages like Java.

double d = 2.519;
String s = NumberFormat.currency().format(d);
print(s);

returns USD2.52

s = NumberFormat('#.00').format(d);

returns 2.52

Since your are dealing with money, you should probably use NumberFormat.currency, which would add the currency symbol for the current locale.

Paul
  • 352
  • 2
  • 3
1

Your question is more about how Dart handles the type double. Something like the following might work depending on your use-case:

void main() {
  double num = 2.50138263;
  
  num = double.parse(num.toStringAsFixed(2));
  
  print(num);
}

More info about how Dart handles double can be found here.

Hesam Chobanlou
  • 331
  • 1
  • 3