Dart num toStringAsPrecision()
Syntax & Examples


num.toStringAsPrecision() method

The `toStringAsPrecision` method in Dart converts this number to a double and returns a string representation with exactly the specified number of significant digits.


Syntax of num.toStringAsPrecision()

The syntax of num.toStringAsPrecision() method is:

 String toStringAsPrecision(int precision) 

This toStringAsPrecision() method of num 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

num.toStringAsPrecision() returns value of type String.



✐ Examples

1 String representation with 5 significant digits

In this example,

  1. We create a num variable num1 with the value 123.456789.
  2. We use the toStringAsPrecision() method with 5 significant digits to get its string representation.
  3. We then print the result to standard output.

Dart Program

void main() {
  num num1 = 123.456789;
  String precisionString = num1.toStringAsPrecision(5);
  print('String representation of $num1 with 5 significant digits: $precisionString');
}

Output

String representation of 123.456789 with 5 significant digits: 123.46

2 String representation with 2 significant digits

In this example,

  1. We create a num variable num1 with the value 123.456789.
  2. We use the toStringAsPrecision() method with 2 significant digits to get its string representation.
  3. We then print the result to standard output.

Dart Program

void main() {
  num num1 = 123.456789;
  String precisionString = num1.toStringAsPrecision(2);
  print('String representation of $num1 with 2 significant digits: $precisionString');
}

Output

String representation of 123.456789 with 2 significant digits: 1.2e+2

Summary

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