Dart double toStringAsFixed()
Syntax & Examples
double.toStringAsFixed() method
The `toStringAsFixed` method converts the given number to a string with a fixed number of decimal places.
Syntax of double.toStringAsFixed()
The syntax of double.toStringAsFixed() method is:
String toStringAsFixed(int fractionDigits) This toStringAsFixed() method of double returns a decimal-point string-representation of this.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
fractionDigits | required | the number of digits after the decimal point |
Return Type
double.toStringAsFixed() returns value of type String.
✐ Examples
1 Convert a double to a string with two decimal places
In this example,
- We define a double
numwith a value of3.14159. - We call the
toStringAsFixedmethod onnumwith2as the number of digits after the decimal point. - We print the result to standard output.
Dart Program
void main() {
double num = 3.14159;
String result = num.toStringAsFixed(2);
print('Result: $result');
}Output
Result: 3.14
2 Convert a double to a string with three decimal places
In this example,
- We define a double
numwith a value of123.456789. - We call the
toStringAsFixedmethod onnumwith3as the number of digits after the decimal point. - We print the result to standard output.
Dart Program
void main() {
double num = 123.456789;
String result = num.toStringAsFixed(3);
print('Result: $result');
}Output
Result: 123.457
3 Convert a num to a string with four decimal places
In this example,
- We define a num
numwith a value of987.654321. - We call the
toStringAsFixedmethod onnumwith4as the number of digits after the decimal point. - We print the result to standard output.
Dart Program
void main() {
double num = 987.654321;
String result = num.toStringAsFixed(4);
print('Result: $result');
}Output
Result: 987.6543
Summary
In this Dart tutorial, we learned about toStringAsFixed() method of double: the syntax and few working examples with output and detailed explanation for each example.