Hello eveyone,

I am trying to round some numbers.
If the number is 1.56454
I want it rounded to 1.56

if the number is 1
I want it to show 1.00

If the number is 1.4
I want it rounded to 1.40

I tried:
$theStatFormulaTemp=round($theStatFormulaTemp, 2);

But this seems to only round the first case the way I want it.
It will leave the number 1 as 1
And the number 1.4 as 1.4

I tried this:
$theStatFormulaTemp = number_format($theStatFormulaTemp, 2, '.', '');

This will round:
1.56454 to 1.56
AND 1 to 1
AND 1.4 to 1.

*note in the case 1.4 it doesn't give me the 1.4 even, it just gives me 1. with no 4

Any ideas what i'm doing wrong? Can anyone point me in the right direction?

OOhh also, I don't just want to print this number....
I want to assign the formatted number eg) 1.40
to a variable, and then I take the value and print it.

So like this:
// do my thing to format the number to 2 decimals
$formattedNumber=// whatever my formatted number is (including decimals)

then it is passed to a new function and printed:
print"$formattedNumber";

So a solution like this:
printf("%.2f", $test);

would not work, cause that just prints it.

Any help is greatly appreciated.
Thanks for your time!!

    Well use sprintf() function if U want to assign this value to variable, it must work as I think.

      Sorry if this isn't the answer you're looking for, but 🙂 - in response to the title.
      To round a float to 2 DP, you need to use the round() command as such (didnt think it would be this easy did ya 😉).

      // just so you can see whats going on, i have split it up a little
      
      $first_var = <the float you want to divide>;
      $second_var = <the number of decimal places>;
      
      round($first_var , $second_var);

      Hope this helps 🙂

        it will round, but will not add zeroes to integer value, after it this string must be formatted, with printf() or sprintf() functions, it depends what she(he) wants to do futher with this value, just print it or put to variable, as I understood from post she(he) have to use sprintf()

          Write a Reply...