PHP意外地扩展了float值 [英] PHP expanding float value unexpectedly

查看:95
本文介绍了PHP意外地扩展了float值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP扩展float值时遇到问题,例如241.09变为241.0899999999.问题是,扩展值包含在签名中,因此扩展导致我的签名与具有原始未扩展形式的实际数据匹配时不匹配.如何防止四舍五入?我的代码部分如下:

Am having an issue where PHP expands the float value e.g. 241.09 becomes 241.0899999999. The issue is, the expanded value is included in a signature, thus the expansion is causing my signature to have a mismatch when matching with the actual data which has the original unexpanded form. How do I prevent the rounding off? My code section is as below:

round(floatval($resultParams["AvailableFunds"]), 2)

以某种方式,即使应用了舍入功能后,仍然会发生扩展.我该如何防止呢?

Somehow, even after applying the round function, the expansion still occurs. How do I prevent that??

推荐答案

它是由 PHP浮点精度:

浮点数的精度有限.

Floating point numbers have limited precision.

一个解决方案可能是仅使用整数,例如将浮点数123.45保存为12345,并在需要使用display时将其除以100并将其传递给number_format函数:

A solution may be to use only integer, e.g. save the float 123.45 as 12345 and when you need to use display it divide it by 100 and pass it to the number_format function:

$myNumView = number_format($myNum/100, 2, '.', '')+0;

这样做,number_format返回一个格式为1234567.89的字符串,然后通过执行+0 PHP将其转换为float(由于PHP

By doing this, number_format returns a string formatted as 1234567.89, then by doing +0 PHP converts it to float (due to the PHP Type Juggling) and removes the rightmost 0 in the decimal part of the number:

$a = '35';
$b = '-34.99';
echo $myNum = ($a + $b);
echo '<br>';
echo $myNumView = number_format($myNum, 4, '.', '')+0;

返回:

0.009999999999998
0.01

而且,为什么从带有floatval的字符串中获取AvailableFunds?看来AvailableFunds是一个包含资金金额和其他文本的字符串.我认为这对节省资金数额是一个糟糕的实现.最好在专用字段中将值保存为float.

And also, why does you get AvailableFunds from a string with floatval? It seems that AvailableFunds is a string containing the amount of fund and other text. I think this is a bad implementation on how saving the fund amount. It's better to save the value as is in a dedicated field as float.

这篇关于PHP意外地扩展了float值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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