3

I have a decimal value of length 15,4 in my database.

I have a number -23.425 I am trying to round down to -23.42

I have tried the following ways but they all seem to round up to -23.43:

 sprintf("%.2f", $discountQueryResult['value'])

 floor($discountQueryResult['value']*100)/100 

Is there any other way to drop the 3rd decimal place?

Sackling
  • 1,780
  • 5
  • 37
  • 71
  • even in excel when i decrease digits on the cell including 23.425 it changes to 23.43 – Sackling Sep 10 '19 at 00:13
  • Keep in mind, that floating point numbers can't necessarily represent decimal digits precisely like this. You many want to use exact types instead. Have a look at https://floating-point-gui.de/ – RoToRa Sep 10 '19 at 07:42

2 Answers2

1

You're trying to round a negative number. Rounding down a negative number with floor() will increase its absolute value; remember, -23.43(0) is less than -23.425!

Instead, you're looking to round up its value with ceil():

echo ceil(-23.425 * 100) / 100; // -23.42

This can be seen working here.

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
0

Try following code

return $rounded = 0.01 * (int)($number * 100);

There are other answers here like following

1) PHP dropping decimals without rounding up

2) PHP: get number of decimal digits

3) Remove a decimal place in PHP

Mike Ross
  • 2,942
  • 5
  • 49
  • 101