To acquire the closest string representation with exactly N digits after the decimal point, use toStringAsFixed()
.
In Dart, the toStringAsFixed()
method converts this
number to a double
before computing the string representation.
String toStringAsFixed(int fractionDigit);
fractionDigit
must be an integer satisfying: 0 <= fractionDigit <= 20
This method returns an exponential representation computed by toStringAsExponential()
if the absolute value of this
number is higher than or equal to 10^21. Otherwise, the closest string representation of fractionDigit
is presented exactly after the decimal point is returned.
The decimal point is omitted if
fractionDigit
equals 0.
The following code shows how to use the method toStringAsFixed()
in Dart:
void main(){// printing upto 2 decimal pointsdouble num1 = double.parse((56.4118238).toStringAsFixed(2));print(num1);// printing upto 3 decimal pointsdouble num2 = double.parse((-56.4018238).toStringAsFixed(3));print(num2);// printing upto 3 decimal pointsprint((50000000000000000).toStringAsFixed(3));// printing upto 0 decimal pointsprint((10.45).toStringAsFixed(0));}
We use the method toStringAsFixed()
to get the closest string representation with exactly N digits after the decimal point, then parse the result to double.