-2

I have a php variable that I would like to round up if it closest value is i.e

113.845602277119 so this var would become 113.85

and round down if var is i.e 270.27388400703 would become 270.27 NOT 270.28

I presume i'll need a function to check the decimal value and update accordingly?

or a better example of what I want.

i.e this dynamic number 16.94502 I want this to round down to 16.94 the .9452 is closest to .95 but as the var is dynamic I need a check to do the inverse, other times the var could be 41.1378 is closest to .14 and so I want a round up

Alex McPherson
  • 3,185
  • 3
  • 30
  • 41

3 Answers3

0

Use PHP round() function:

Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

Example:

echo round(113.845602277119,2); // 113.85
echo round(270.27388400703,2); // 270.27
Brett Gregson
  • 5,867
  • 3
  • 42
  • 60
0

Hi You can use number_format for this

echo number_format("113.845602277119",2)."<br>"; // 113.85


echo number_format("270.27388400703",2)."<br>"; // 270.27

or round function

   echo round("113.845602277119",2)."<br>"; // 113.85


    echo round("270.27388400703",2)."<br>"; // 270
Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
0

The PHP round function is perfect for this kind of work, you simply pass it the number and as a 2nd parameter pass it how many numbers to round to

You can view the documentation here http://php.net/manual/en/function.round.php

round(270.27388400703, 2)

round(113.845602277119, 2)
Mark Twigg
  • 301
  • 1
  • 8
  • i.e this dynamic number 16.94502 I want this to round down to 16.94 the .9452 is closest to .95 but as the var is dynamic I need a check to do the inverse, other times the var could be 41.1378 is closest to .14 and so I want a round up – Alex McPherson Aug 11 '16 at 10:28
  • @AlexMcPherson this is exactly what round() does, run the above code you will see it works fine. You can simply replace the number with your variable if that what you mean round($var, 2); – Mark Twigg Aug 11 '16 at 10:31
  • Thats what I thought but I am not getting that result. It must be some other issue in my code. – Alex McPherson Aug 11 '16 at 10:36