PHP中浮点值的问题
我的浮点值转换有问题。我在班级中有一个私有财产,价值为317.46。如果我将该值乘以100,则应该具有317.46的值,这似乎就是发生的,但是当我使用JSON_ENCODE时,它会返回另一个值,稍小。这是调试控制台的结果:
$this->valor
317.46
$this->valor * 100
31746
json_encode($this->valor * 100)
"31745.99999999999996"
我知道这是由于浮点的存储方式,但是在这种情况下,我需要将其“渲染”为整数,否则它将在API中产生错误打电话。在其他语言中,我会将其转换为int值,或使用十进制
datatype,例如c#
中的数据类型,但据我所知,在PHP中不可用。
I'm having a problem with a floating point value conversion. I have a private property in a class with a value of 317.46. If I multiply this value by 100, I should have the value of 317.46, and that's what seems to be happening, but when i use json_encode it returns another value, slightly smaller. This is the result from the debug console:
$this->valor
317.46
$this->valor * 100
31746
json_encode($this->valor * 100)
"31745.99999999999996"
I known this is due to the way floating points are stored, but in this case I need it to be 'rendered' as a integer, otherwise it will generate an error in the API I'm calling. In other languages I would convert it to a int value, or use a decimal
datatype, like in c#
, but it's not available in PHP as far as I know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
rough()
从浮点表示中删除圆形错误。如果这是金钱,最好首先将便士用作代表,以避免出现在小数分数转换和转换的问题。
Use
round()
to remove the round-off error from floating point representation.If this is money, it's a good idea to use pennies as the representation in the first place, to avoid problems from converting to and from decimal fractions.