2 位小数的 PHP 浮点数:.00

php
2022-08-30 09:15:58

当我做这个类型转换时:

(float) '0.00';

我得到.如何获取并仍然将数据类型作为浮点数?00.00


答案 1

浮点数没有或:这些是内部(IEEE754)二进制格式的不同字符串表示形式,但浮点数是相同的。00.00

如果要将 float 表示为“0.00”,则需要使用 number_format 将其格式化为字符串:

$numberAsString = number_format($numberAsFloat, 2);

答案 2

据我所知,PHP没有解决方案可以解决这个问题。此线程中给出的所有其他(上面和下面)答案都是无稽之谈。

number_format函数返回一个字符串作为 PHP.net 自己的规范中编写的结果。

像 floatval/doubleval 这样的函数会返回整数,如果你给出值 3.00 。

如果你做类型杂耍,那么你会得到一个整数作为结果。

如果你使用 round(), 那么你会得到一个整数作为结果。

我能想到的唯一可能的解决方案是使用您的数据库将类型转换为浮点型。例如,MySQL:

SELECT CAST('3.00' AS DECIMAL) AS realFloatValue;

使用抽象层执行此命令,该抽象层返回浮点数而不是字符串,然后就可以了。


JSON 输出修改

如果您正在寻找一种解决方案来修复JSON输出以保留2位小数,那么您可以使用后格式化,如下面的代码所示:

// PHP AJAX Controller

// some code here

// transform to json and then convert string to float with 2 decimals
$output = array('x' => 'y', 'price' => '0.00');
$json = json_encode($output);
$json = str_replace('"price":"'.$output['price'].'"', '"price":'.$output['price'].'', $json);

// output to browser / client
print $json;
exit();

返回到客户端/浏览器:

{"x":"y","price":0.00}

推荐