Rounding value correctly

intval() does not round values correctly!!!!
As for C++, it simply converts to int and ignores decimal places. If you want a source value of say 5.6 to be converted to an integer of 6 and not 5, then use:

  $MyIntValue = intval(round(5.6));    //<<< intval() because round() outputs a float

Round down

$MyVariable = floor(56.78);    //Returns 56

Round Up

$MyVariable = ceil(56.78);    //Returns 57

Round to a specific number of decimal places

echo round(12.3456789, 3);    //Will print: 12.346

Value output vs string output

//Force to 2 decimal places (outputs as a string, so "6.30")
  $MyString = number_format("6.3",2);  //Will display 6.30

//Force to 2 decimal places (outputs as a number, so 6.30)
  $MyValue = round("6.3456",2);  //Will output 6.30
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *