0

I multiply the number 762 by the number 0.11 But the result is 83.82000000000001 (not correct)

How to avoid this number 83.82000000000001.

I want to get the correct number 83.82.

I don't want to specify decimals because other math operation may return number with different decimals.

void main(){
  int  number = 762;
  print('number= $number');
  double d =  0.11 * number;
  print('number * 0.11 = $d');
  print('number * 0.11 = ${d.toString()}');
  
  // I don't want to specify the decimals
  print('this is the correct result= ${d.toStringAsFixed(2)}'); 
}

Result:

number= 762
number * 0.11 = 83.82000000000001
number * 0.11 = 83.82000000000001
this is the correct result= 83.82
julemand101
  • 28,470
  • 5
  • 52
  • 48

1 Answers1

2

The answer is correct based on the limitations of the double type, which you can read more about here: Dart double division precision

But if you want to do the calculation with infinite precision, you can use the decimal package to do e.g. the following:

import 'package:decimal/decimal.dart';

void main() {
  Decimal number = Decimal.fromInt(762);
  print('number= $number');
  Decimal d = Decimal.parse('0.11') * number;
  print('number * 0.11 = $d');
}

Which will output:

number= 762
number * 0.11 = 83.82
number * 0.11 = 83.82
julemand101
  • 28,470
  • 5
  • 52
  • 48