I was having a hard time finding a way to actually separate the dollar amount and the amount after the decimal. I think I figured it out mostly and thought to share if any of yall were having trouble
So basically...
如果价格是1234.44整数是1234小数是44
如果价格是1234.01整数是1234小数是01或
如果价格是1234.10整数是1234小数是10
等等
$price = 1234.44;
$whole = intval($price); // 1234
$decimal1 = $price - $whole; // 0.44000000000005 uh oh! that's why it needs... (see next line)
$decimal2 = round($decimal1, 2); // 0.44 this will round off the excess numbers
$decimal = substr($decimal2, 2); // 44 this removed the first 2 characters
if ($decimal == 1) { $decimal = 10; } // Michel's warning is correct...
if ($decimal == 2) { $decimal = 20; } // if the price is 1234.10... the decimal will be 1...
if ($decimal == 3) { $decimal = 30; } // so make sure to add these rules too
if ($decimal == 4) { $decimal = 40; }
if ($decimal == 5) { $decimal = 50; }
if ($decimal == 6) { $decimal = 60; }
if ($decimal == 7) { $decimal = 70; }
if ($decimal == 8) { $decimal = 80; }
if ($decimal == 9) { $decimal = 90; }
echo 'The dollar amount is ' . $whole . ' and the decimal amount is ' . $decimal;
This way is not involving string based functions, and is preventing accuracy problems which may arise in other math operations (such as having 0.49999999999999 instead of 0.5).
Haven't tested thoroughly with extreme values, but it works fine for me for price calculations.
但是,小心! 现在从 -5.25得到: 整数部分: -5; 十进制部分: -25
In case you want to get always positive numbers, simply add abs() before the calculations: