Python十进制与C#十进制精度 [英] Python Decimal vs C# decimal precision

查看:75
本文介绍了Python十进制与C#十进制精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经被问了无数次了,我遇到了很多博客和答案,但这使我不寒而栗.我只想将两个十进制数乘以100,就可以摆脱它的十进制数:

I know this has been asked numerous times and I've come across many blogs and SO answers but this one's making me pull my hair out. I just want to multiply a two decimal number by 100 so I get rid of its decimals:

>>> 4321.90 * 100
432189.99999999994
>>> Decimal(4321.90) * Decimal(100)
Decimal('432189.9999999999636202119291')

我不敢对这种看似微不足道的操作使用四舍五入.会安全吗?如果精度问题对我不利,结果接近xxx.5,该怎么办?会发生吗?我确实在二进制级别理解了该问题,但是我来自C#,而.Net的 decimal 类型没有这个问题:

I'm scared to use rounding for such seemingly trivial operation. Would it be safe? What if the precision problem plays tricks on me and the result is close to xxx.5? Can that happen? I do understand the problem at the binary level, but I come from C# and I don't have that problem with .Net's decimal type:

decimal x = 4321.90m;
decimal y = 100m;
Console.WriteLine(x * y);
432190,00

我认为Python的十进制模块应该可以解决该问题.我将要将初始值转换为字符串,并通过字符串操作进行数学运算,我对此感到难过...

I thought Python's decimal module was supposed to fix that. I'm about to convert the initial value to string and do the math with string manipulations, and I feel bad about it...

推荐答案

使用Python失败的主要原因是因为 4321.90 被解释为float(此时您失去了精度),然后将其强制转换为十进制在运行时.使用C#,将 4321.90m 解释为十进制开头.Python根本不支持将小数作为内置结构.

The main reason it fails with Python is because 4321.90 is interpreted as float (you lose precision at that point) and then casted to Decimal at runtime. With C# 4321.90m is interpreted as decimal to begin with. Python simply doesn't support decimals as a built-in structure.

但是有一种简单的方法可以使用Python修复它.只需使用字符串:

But there's an easy way to fix that with Python. Simply use strings:

>>> Decimal('4321.90') * Decimal('100')
Decimal('432190.00')

这篇关于Python十进制与C#十进制精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆