php - number_format only if not zero

333

I want to show one decimal of a float if it has non zero decimals.

What is the most elegant way to do this?

100.00 -> 100
99.45 -> 99.5
99.44 -> 99.4
11.30 -> 11.3
2.00 -> 2
11.02 -> 11
13.05 -> 13.1
734

Answer

Solution:

ini_set("precision", 8); /* low enough; eventually if needed */
var_dump((string)round($float, 1));

this should do the task

633

Answer

Solution:

use in the following manner.

$x = "99.44";  // example value
$y =  number_format((float)$x, 1, '.', '');
echo str_replace(".0","",$y);
587

Answer

Solution:

I prefer this way:

$num = 100.1;
echo (floor($num) == $num) ? $num : number_format($num,1);

691

Answer

Solution:

$rounded = (!is_int($number)) ? round($number, 1) : round($number);

I have tested the above with your sample data and the outputs are as follows:

100.00 > 100
99.45 > 99.5
99.44 > 99.4
11.30 > 11.3
2.00 > 2
11.02 > 11
13.05 > 13

People are also looking for solutions to the problem: MAMP running, PHP not

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.