code_junkie

How to round/ceil/floor a bcmath number in PHP?

Nov 11th, 2011
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. echo ceil(31497230840470473074370324734723042.6);
  2.  
  3. // Expected result
  4. 31497230840470473074370324734723043
  5.  
  6. // Prints
  7. <garbage>
  8.  
  9. $x = '31497230840470473074370324734723042.9';
  10.  
  11. bcscale(100);
  12. var_dump(bcFloor($x));
  13. var_dump(bcCeil($x));
  14. var_dump(bcRound($x));
  15.  
  16. function bcFloor($x)
  17. {
  18. $result = bcmul($x, '1', 0);
  19. if ((bccomp($result, '0', 0) == -1) && bccomp($x, $result, 1))
  20. $result = bcsub($result, 1, 0);
  21.  
  22. return $result;
  23. }
  24.  
  25. function bcCeil($x)
  26. {
  27. $floor = bcFloor($x);
  28. return bcadd($floor, ceil(bcsub($x, $floor)), 0);
  29. }
  30.  
  31. function bcRound($x)
  32. {
  33. $floor = bcFloor($x);
  34. return bcadd($floor, round(bcsub($x, $floor)), 0);
  35. }
  36.  
  37. function bcceil($number)
  38. {
  39. if ($number[0] != '-')
  40. {
  41. return bcadd($number, 1, 0);
  42. }
  43.  
  44. return bcsub($number, 0, 0);
  45. }
  46.  
  47. function bcfloor($number)
  48. {
  49. if ($number[0] != '-')
  50. {
  51. return bcadd($number, 0, 0);
  52. }
  53.  
  54. return bcsub($number, 1, 0);
  55. }
  56.  
  57. function bcround($number, $precision = 0)
  58. {
  59. if ($number[0] != '-')
  60. {
  61. return bcadd($number, '0.' . str_repeat('0', $precision) . '5', $precision);
  62. }
  63.  
  64. return bcsub($number, '0.' . str_repeat('0', $precision) . '5', $precision);
  65. }
  66.  
  67. assert(bcceil('4.3') == ceil('4.3')); // true
  68. assert(bcceil('9.999') == ceil('9.999')); // true
  69. assert(bcceil('-3.14') == ceil('-3.14')); // true
  70.  
  71. assert(bcfloor('4.3') == floor('4.3')); // true
  72. assert(bcfloor('9.999') == floor('9.999')); // true
  73. assert(bcfloor('-3.14') == floor('-3.14')); // true
  74.  
  75. assert(bcround('3.4', 0) == number_format('3.4', 0)); // true
  76. assert(bcround('3.5', 0) == number_format('3.5', 0)); // true
  77. assert(bcround('3.6', 0) == number_format('3.6', 0)); // true
  78. assert(bcround('1.95583', 2) == number_format('1.95583', 2)); // true
  79. assert(bcround('5.045', 2) == number_format('5.045', 2)); // true
  80. assert(bcround('5.055', 2) == number_format('5.055', 2)); // true
  81. assert(bcround('9.999', 2) == number_format('9.999', 2)); // true
Add Comment
Please, Sign In to add comment