Sackling
Sackling

Reputation: 1820

Drop decimal place without rounding value

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?

Upvotes: 3

Views: 389

Answers (2)

Obsidian Age
Obsidian Age

Reputation: 42374

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.

Upvotes: 1

Mike Ross
Mike Ross

Reputation: 2972

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

Upvotes: 0

Related Questions