Mal*_*ala 8 php floating-point casting money-format
作为输入,我想接受以下任何一项:"$ 12.33","14.92","$ 13","17","14.00001".作为输出,我分别想要1233,1492,1300,1700和1400.这显然不像看起来那么容易:
<?php
$input = '$64.99'; // value is given via form submission
$dollars = str_replace('$', '', $input); // get rid of the dollar sign
$cents = (int)($dollars * 100) // multiply by 100 and truncate
echo $cents;
?>
Run Code Online (Sandbox Code Playgroud)
这输出6498而不是6499.
我假设这与浮点值的不准确有关,并且避免这些是我首先转换为整数美分的全部原因.我想我可以使用逻辑,比如"摆脱$符号,检查是否有小数点,如果是这样,检查填充到2之后有多少个字符,然后截断,然后删除句点,如果没有一个附加两个零,并希望最好的"但使用字符串操作这似乎是荒谬的.
当然从表单中获取货币价值并将其作为美分存储在数据库中是一种常见的用例.当然,有一种"合理"的做法.
对?.....对?<
cdh*_*wie 31
考虑使用BC Math扩展,它可以进行任意精度的数学运算.特别是bcmul()
:
<?php
$input = '$64.99';
$dollars = str_replace('$', '', $input);
$cents = bcmul($dollars, 100);
echo $cents;
?>
Run Code Online (Sandbox Code Playgroud)
输出:
6499
Run Code Online (Sandbox Code Playgroud)
$input[] = "$12.33";
$input[] = "14.92";
$input[] = "$13";
$input[] = "17";
$input[] = "14.00001";
$input[] = "$64.99";
foreach($input as $number)
{
$dollars = str_replace('$', '', $number);
echo number_format((float)$dollars*100., 0, '.', '');
}
Run Code Online (Sandbox Code Playgroud)
给出:
1233
1492
1300
1700
1400
6499
Run Code Online (Sandbox Code Playgroud)
留意像“$0.125”这样的极端情况。我不知道你想如何处理这些。