Dart double toStringAsPrecision()
Syntax & Examples

double.toStringAsPrecision() method

Converts the given numeric value to a double and returns a string representation with the specified number of significant digits.


Syntax of double.toStringAsPrecision()

The syntax of double.toStringAsPrecision() method is:

 String toStringAsPrecision(int precision) 

This toStringAsPrecision() method of double converts this to a double and returns a string representation with exactly precision significant digits.

Parameters

ParameterOptional/RequiredDescription
precisionrequiredthe number of significant digits

Return Type

double.toStringAsPrecision() returns value of type String.



✐ Examples

1 Example with 5 significant digits

In this example,

  1. We create a numeric value numValue with the value 12345.6789.
  2. We then use the toStringAsPrecision() method with 5 significant digits specified.
  3. We print the precision string representation to standard output.

Dart Program

void main() {
  num numValue = 12345.6789;
  String precisionStr = numValue.toStringAsPrecision(5);
  print(precisionStr);
}

Output

12346

2 Example with 10 significant digits

In this example,

  1. We create a numeric value numValue with the value 12345.6789.
  2. We then use the toStringAsPrecision() method with 10 significant digits specified.
  3. We print the precision string representation to standard output.

Dart Program

void main() {
  num numValue = 12345.6789;
  String precisionStr = numValue.toStringAsPrecision(10);
  print(precisionStr);
}

Output

12345.67890

3 Example with 2 significant digits

In this example,

  1. We create a numeric value numValue with the value 12345.6789.
  2. We then use the toStringAsPrecision() method with 2 significant digits specified.
  3. We print the precision string representation to standard output.

Dart Program

void main() {
  num numValue = 12345.6789;
  String precisionStr = numValue.toStringAsPrecision(2);
  print(precisionStr);
}

Output

1.2e+4

Summary

In this Dart tutorial, we learned about toStringAsPrecision() method of double: the syntax and few working examples with output and detailed explanation for each example.