英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论