当我进行如下类型转换:
(float) '0.00';
我得到了 0
。如何获得 0.00
并仍然保持数据类型为浮点数?
当我进行如下类型转换:
(float) '0.00';
我得到了 0
。如何获得 0.00
并仍然保持数据类型为浮点数?
浮点数没有0
或0.00
:它们是内部的(IEEE754)二进制格式的不同字符串表示方式,但浮点数是相同的。
如果您想将浮点数表示为“0.00”,您需要将其格式化为字符串,使用number_format:
$numberAsString = number_format($numberAsFloat, 2);
SELECT CAST('3.00' AS DECIMAL) AS realFloatValue;
使用一个抽象层,返回浮点数而不是字符串,然后你就可以执行它了。
如果您正在寻找解决方案来修复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}
"
字符,则可以在使用 number_format
和 json 编码之后,只需使用以下代码即可:$json = str_replace('"', '', $json);
- Nabi K.A.Z.number_format
返回一个字符串;而无论何时你想要查看一个数字,都需要一个字符串。如果你看过整数或浮点数的二进制表示,它不会看起来像“2”、“2.0”、“2.00”或任何其他东西;这些都是数字的人类可读表示。 - IMSoP0.00实际上是0。如果您需要在echo时保留0.00,则可以使用number_format函数,如下所示:
number_format($number, 2);
例如:
$myNonFormatedFloat = 5678.9
$myGermanNumber = number_format($myNonFormatedFloat, 2, ',', '.'); // -> 5.678,90
$myAngloSaxonianNumber = number_format($myNonFormatedFloat, 2, '.', ','); // -> 5,678.90
number_format()
函数来改变数字的显示方式。它将返回一个字符串,原始变量的类型不受影响。$nom="5695.5";
number_format((float)($nom), 2, '.', ','); // -> 5,695.50
$nom="5695.5215";
number_format((float)($nom), 2, '.', ','); // -> 5,695.52
$nom="5695.12";
number_format((float)($nom), 0, '.', ','); // -> 5,695
$nom="5695.12";
number_format((float)round($nom), 2, '.', ','); // -> 5,695.00
$nom="5695.52";
number_format((float)round($nom), 2, '.', ','); // -> 5,696.00
(请注意,在此上下文中,“整数”不仅仅是“整数”的同义词,它是一种特定的数据类型,具有自己的规则,用于表示内存中的值。)
相比之下,字符串“2”看起来像这样:
00110010
而字符串“2.00”看起来像这样:
00110010001011100011000000110000
(在PHP程序中,实际上会有额外的内存信息,例如类型指示器,但这在这里并不重要。)
JSON_PRESERVE_ZERO_FRACTION
,它会将浮点数格式化为一个带有尾随 ".0" 的整数,例如:$example = ['int' => 2, 'float' => 2.0];
echo json_encode($example);
# => {"int":2,"float":2}
echo json_encode($example, JSON_PRESERVE_ZERO_FRACTION);
# => {"int":2,"float":2.0}
你可以尝试这个,它会对你有用
number_format(0.00, 2)
你可以使用 round 函数
round("10.221",2);
将返回 10.22
0.00
不是有效的浮点数,请参考 http://en.wikipedia.org/wiki/IEEE_floating_point。 - Baba