Search code examples
phpnumbersdigit

PHP one digit after decimal point for real numbers and no digits for integer values


What is the best solution to convert a number to:

  1. one digit after decimal point if that number is a real number
  2. no digits, no decimal point if the number is an integer

Example:

if ($num == 8.2) //display 8.2
if ($num == 8.0) //display 8

Note: I won't have numbers like 8.22 or 8.02. I will have this type of numbers:

1, 1.2, 1.4 ... 2.6, 2.8, 3 ....9.8, 10


Solution

  • If you know for sure that all of your numbers will be in that format, you should be able to just use round. (Normally, round does not work well for formatting, but in this case it should do the job.)

    foreach ([8, 8.2, 1, 1.2, 1.4, 2.6, 2.8, 3, 9.8, 10] as $number) {
        echo round($number, 1) . PHP_EOL;
    }
    

    Some might assume otherwise, but echo round(8.0, 1); displays 8, not 8.0.