Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between double.toStringAsFixed and toStringAsPrecision in dartlang?

Tags:

dart

I want know what's difference between these two methods. I thought toStringAsFixed trims the number but from the examples in doc, both are rounding the numbers.

Here's the related issue: https://github.com/dart-lang/sdk/issues/25947

like image 507
mirkancal Avatar asked Aug 22 '19 12:08

mirkancal


People also ask

What is a double in Dart?

In the Dart programming language, double is a data type that stores decimal numbers (fractional numbers). For each double variable, eight bytes are allocated in the memory. If you try to assign any integer value to the double variable then, by default, it will be cast to the double data type.

How do you convert a string to a double in flutter?

For converting a String to a double, the parse() static method of double class can be used. String source, [@deprecated double onError(String source)?] );


1 Answers

1. Double.toStringAsPrecision(int)

Converts a num to a double and returns a String representation with exactly precision significant digits.

The parameter precision must be an integer satisfying: 1 <= precision <= 21.

Examples:

1.59.toStringAsPrecision(1); // 2
1.59.toStringAsPrecision(2); // 1.6
1.59.toStringAsPrecision(3); // 1.59
1.59.toStringAsPrecision(4); // 1.590
1e15.toStringAsPrecision(3);    // 1.00e+15
1234567.toStringAsPrecision(3); // 1.23e+6
1234567.toStringAsPrecision(9); // 1234567.00
12345678901234567890.toStringAsPrecision(20); // 12345678901234567168
12345678901234567890.toStringAsPrecision(14); // 1.2345678901235e+19
0.00000012345.toStringAsPrecision(15); // 1.23450000000000e-7
0.0000012345.toStringAsPrecision(15);  // 0.00000123450000000000

2. Double.toStringAsFixed(int)

It also rounds the number but after the decimal place and return the result according to the int value you provide.

double d = 1.59;
String fixed1 = d.toStringAsFixed(1); // 1.6
String fixed2 = d.toStringAsFixed(2); // 1.59
String fixed3 = d.toStringAsFixed(3); // 1.590
String fixed4 = d.toStringAsFixed(4); // 1.5900
like image 194
CopsOnRoad Avatar answered Oct 24 '22 18:10

CopsOnRoad