MySQL & PHP decimal precision wrong

前端 未结 3 1473
后悔当初
后悔当初 2021-01-28 06:10

24151.40 - 31891.10 = -7739.699999999997

I grab these two numbers from a MySQL table with the type as decimal(14,2) 24151.40 31891.10 It is saved exactly as stated abov

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-28 07:00

    PHP doesn't have a decimal type like MySQL does, it uses floats; and floats are notorious for being inaccurate.

    To cure this, look into number_format, e.g.:

    echo number_format(24151.40 - 31891.10, 2, '.', '');
    

    For more accurate number manipulation, you could also look at the math extensions of PHP:

    http://www.php.net/manual/en/refs.math.php

提交回复
热议问题