Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
method
communitycreator

What is toStringAsFixed() method in Dart?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

fractionDigit must 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 fractionDigit equals 0.

Code

The following code shows how to use the method toStringAsFixed() in Dart:

void main(){
// printing upto 2 decimal points
double num1 = double.parse((56.4118238).toStringAsFixed(2));
print(num1);
// printing upto 3 decimal points
double num2 = double.parse((-56.4018238).toStringAsFixed(3));
print(num2);
// printing upto 3 decimal points
print((50000000000000000).toStringAsFixed(3));
// printing upto 0 decimal points
print((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.

RELATED TAGS

dart
method
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring