Round decimals with PHP

Asked

Viewed 453 times

1

I need to round decimal numbers down, except for when the decimal place is 5, for example 1.2 I want to round off to 1 and when the number is 1.5 I want to keep the value. I know only 3 functions of PHP round: floor, Ceil and round but none works that way. The function floor round down but round 1.5 to 1. Another detail I’m working with only 1 decimal place. I tried to create a function to do this treatment but unfortunately I could not.

// Utilizando as funções nativas do PHP.

echo round( 1.2 ); // 1
echo round( 1.5 ); // 2
echo round( 1.6 ); // 2

echo ceil( 1.2 ); // 2
echo ceil( 1.5 ); // 2
echo ceil( 1.6 ); // 2

echo floor( 1.2 ); // 1
echo floor( 1.5 ); // 1
echo floor( 1.6 ); // 1

// A forma que eu preciso
1.2 => 1
1.5 => 1.5
1.6 => 1.5
  • 5 or higher, Voce wishes to maintain?

  • You can take a look at this answer https://stackoverflow.com/a/6619392/6691854 and make a Function by checking the decimal.

  • 1

    This is almost equal in C#: https://answall.com/a/21941/101

  • @Juliohenrique97 If the decimal is less than 5, I want to round it down, if it is equal to 5 I want to keep it and if it is more than 5 I want to round it down, so: 1.2 => 1, 1.5 => 1.5, 1.6 => 1.5

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.