PHP中浮点值的问题

发布于 2025-01-30 02:24:51 字数 402 浏览 1 评论 0原文

我的浮点值转换有问题。我在班级中有一个私有财产,价值为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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

老街孤人 2025-02-06 02:24:51

使用rough()从浮点表示中删除圆形错误。

echo json_encode(round($this->valor * 100))

如果这是金钱,最好首先将便士用作代表,以避免出现在小数分数转换和转换的问题。

Use round() to remove the round-off error from floating point representation.

echo json_encode(round($this->valor * 100))

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文