Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert long double to string without scientific notation (Dart)

I want to convert a long double to string without scientific notation in Dart, I thought just doing a .toString() would do the trick but it's not the case.

Here's my code:

void main() {  
  double num = 0.00000000196620214137477;
  String numToString = num.toString();
  
  print(num);
  print(numToString);
}

This is what it prints:

1.96620214137477e-9
1.96620214137477e-9

I want a string representation of the number as it was written when defined. So the printout I want after converting to string is:

0.00000000196620214137477

Thanks in advance.

like image 833
Raul Marquez Avatar asked Jul 20 '20 06:07

Raul Marquez


2 Answers

There is no easy way to do what you want directly with the Dart platform libraries, mainly because there is no way to do it in JavaScript.

You can use num.toStringAsFixed(20), but that is limited to 20 digits, and your number needs 23.

One thing you could do is to manipulate the string directly:

String toExact(double value) {
  var sign = "";
  if (value < 0) {
    value = -value; 
    sign = "-";
  }
  var string = value.toString();
  var e = string.lastIndexOf('e');
  if (e < 0) return "$sign$string";
  assert(string.indexOf('.') == 1);
  var offset = int.parse(string.substring(e + (string.startsWith('-', e + 1) ? 1 : 2)));
  var digits = string.substring(0, 1) + string.substring(2, e);
  if (offset < 0) { 
    return "${sign}0.${"0" * ~offset}$digits";
  }
  if (offset > 0) {
    if (offset >= digits.length) return sign + digits.padRight(offset + 1, "0");
    return "$sign${digits.substring(0, offset + 1)}"
        ".${digits.substring(offset + 1)}";
  }
  return digits;
}

Do notice that you can't necessarily get the value as written because not all double values are exact. In this particular case, you seem to be be fine.

like image 50
lrn Avatar answered Nov 14 '22 12:11

lrn


There is another simpler way to do this using decimal package. Recently came across flutter-dart-number-handling-ability question which pointed towards the package.

Example :

double originalNum = 0.00000000196620214137477;
Decimal convertedNum = Decimal.parse(originalNum.toString());
print('originalNum: $originalNum \n convertedNum: $convertedNum');

Output:

originalNum: 1.96620214137477e-9 
convertedNum: 0.00000000196620214137477
like image 30
dev-aentgs Avatar answered Nov 14 '22 11:11

dev-aentgs