12

As input, I want to accept any of the following: "$12.33", "14.92", "$13", "17", "14.00001". As output, I want 1233, 1492, 1300, 1700 and 1400 respectively. This is apparently not as easy as it looks:

<?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;
?>

This outputs 6498 instead of 6499.

I assume this has to do with inaccuracies in floating point values, and avoiding these is the whole reason I'm converting to integer cents in the first place. I suppose I could use logic like "get rid of the $ sign, check if there's a decimal point, if so, check how many characters there are after it padding to two and truncating after that then remove the period, if there wasn't one append two zeros and hope for the best" but using string operations for this seems ridiculous.

Surely taking a monetary value from a form and storing it as cents in a database is a common use case. Surely there is a "reasonable" way of doing this.

Right? .....right? :<

4

7 に答える 7

4
$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, '.', '');
}

与えます:

1233
1492
1300
1700
1400
6499

「$0.125」のような稀なケースに注意してください。あなたがそれらをどのように処理したいかわかりません。

于 2014-02-12T18:13:47.457 に答える
1

ドル記号を削除し、bcmul()を使用して乗算します。

于 2014-02-12T17:58:04.113 に答える