Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make sure a float will always be rounded up with PHP?

I want to make sure a float in PHP is rounded up if any decimal is present, without worrying about mathematical rounding rules. This function would work as follows:

1.1 to 2 1.2 to 2 1.9 to 2 2.3 to 3 2.8 to 3 

I know the round() function exists but I don't see any function for rounding up if any decimal is found. Is there any easy way to do this?

like image 423
Sotiris Avatar asked Feb 23 '11 16:02

Sotiris


People also ask

How do you round a float in PHP?

The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a number DOWN to the nearest integer, look at the floor() function.

How do you round up a float?

Option 1: Python Round Function Python has an inbuilt function round(), which will take the float value and round it off. The round() function takes two parameters: Number and Ndigits (optional). Ndigits represent the number of decimal places to round.

How do I round up in PHP?

The ceil() function rounds a number UP to the nearest integer, if necessary. Tip: To round a number DOWN to the nearest integer, look at the floor() function. Tip: To round a floating-point number, look at the round() function.

How do I stop my floating from rounding?

You need to use the std::fixed output manipulator. (And possibly the std:setprecision() manipulator too.) float is only accurate to about 7 decimal digits not 7 decimal places. Your required output is 10 and 8 digits respectively so there will be rounding/inaccuracy.


1 Answers

Use the ceil function:

$number = ceil(1.1); //2 
like image 171
ircmaxell Avatar answered Sep 24 '22 07:09

ircmaxell