What is toStringAsFixed() method in Dart?
Overview
To acquire the closest string representation with exactly N digits after the decimal point, use toStringAsFixed().
toStringAsFixed() method
In Dart, the toStringAsFixed() method converts this number to a double before computing the string representation.
Syntax
String toStringAsFixed(int fractionDigit);
Parameter
- fractionDigit: indicates the position of the decimal point.
fractionDigitmust be an integer satisfying: 0 <= fractionDigit <= 20
Return type
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
fractionDigitequals 0.
Code
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));}
Explanation
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.