In Dart language multiplying or dividing one number by another returns the wrong result. How do I avoid the error without rounding

huangapple go评论58阅读模式
英文:

In Dart language multiplying or dividing one number by another returns the wrong result. How do I avoid the error without rounding

问题

我将数字 762 乘以数字 0.11,但结果是 83.82000000000001(不正确)。

如何避免出现这个数字 83.82000000000001

我想要获得正确的数字 83.82

我不想指定小数位数,因为其他数学运算可能返回不同小数位数的数字。

void main(){
  int number = 762;
  print('number= $number');
  double d = 0.11 * number;
  print('number * 0.11 = $d');
  print('number * 0.11 = ${d.toString()}');
  
  // 我不想指定小数位数
  print('这是正确的结果= ${d.toStringAsFixed(2)}'); 
}

结果:

number= 762
number * 0.11 = 83.82000000000001
number * 0.11 = 83.82000000000001
这是正确的结果= 83.82
英文:

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

答案1

得分: 2

答案是基于double类型的限制是正确的,你可以在这里阅读更多信息:https://stackoverflow.com/questions/60654642/dart-double-division-precision

但是如果你想要使用无限精度进行计算,你可以使用decimal包来执行以下操作:

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');
}

这将输出:

number= 762
number * 0.11 = 83.82
number * 0.11 = 83.82
英文:

The answer is correct based on the limitations of the double type, which you can read more about here:
https://stackoverflow.com/questions/60654642/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

huangapple
  • 本文由 发表于 2023年7月18日 04:49:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707982.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定