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
num
with a value of3.14159
. - We call the
toStringAsFixed
method onnum
with2
as 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
num
with a value of123.456789
. - We call the
toStringAsFixed
method onnum
with3
as 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
num
with a value of987.654321
. - We call the
toStringAsFixed
method onnum
with4
as 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.