PHP money string conversion to integer error

后端 未结 9 613
小蘑菇
小蘑菇 2021-01-13 21:43

I have a small financial application with PHP as the front end and MySQL as the back end. I have ancient prejudices, and I store money values in MySQL as an integer of cents

相关标签:
9条回答
  • 2021-01-13 22:31

    Casting does not round() as in round-to-nearest, it truncates at the decimal: (int)3.99 yields 3. (int)-3.99 yields -3.

    Since float arithmetic often induces error (and possibly not in the direction you want), use round() if you want reliable rounding.

    0 讨论(0)
  • 2021-01-13 22:33

    When converting from float to integer, the number will be rounded towards zero (src).

    Read the Floating point precision warning.

    0 讨论(0)
  • 2021-01-13 22:34

    The code you posted does the multiplication first, forcing a floating point calculation that introduces error, before converting the value to an integer. Instead, you should avoid floating point arithmetic entirely by reversing the order. Convert to integer values first, then perform the arithmetic.

    Assuming previous code already validated and formatted the input, try this:

    list($bills, $pennies) = explode('.', $dollars);
    $cents = 100 * $bills + $pennies;
    

    Your prejudice against floating point values to represent money is well founded because of truncation and because of values being converted from base-10 to base-2 and back again.

    0 讨论(0)
提交回复
热议问题