paulalexandru
paulalexandru

Reputation: 9530

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

Upvotes: 0

Views: 2905

Answers (3)

Don't Panic
Don't Panic

Reputation: 41810

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.

Upvotes: 5

nerdlyist
nerdlyist

Reputation: 2847

Using floor and some arithmetic and number_format

$num = 8.0;

//8.0 - 8 = 0
//8.2 - 8 = .2
if($num - floor($num)>0) {
    // Leaves 1 decimal
    echo number_format($num,1);
    // or if rounding
    //echo round($num, 1);
} else {
    // Leaves 0 decimal
    echo number_format($num,0);
    // or if rounding
    //echo round($num, 0);
}

Upvotes: 0

Jirka Hrazdil
Jirka Hrazdil

Reputation: 4021

if (abs($num - (int)$num) < 0.001)
  echo (int)$num;
else
  echo number_format($num, 1);

Upvotes: 1

Related Questions