1

I am getting the following output correctly:

<?php echo number_format("12312.312","1"); // Correct Output 12312.3 ?>

but in the following case

<?php echo number_format("12312","1"); // Getting output 12312.0 but requires only 12312 ?>

So basically, I want to control my output i.e. it should add decimal place only if my decimal digit is greater than 0.

1
  • 2
    You are specifying that there should be 1 decimal place. So number_format is giving you one decimal place. What is the problem? Commented Mar 2, 2011 at 1:38

4 Answers 4

2

The second parameter for number_format() takes the number of decimals - so your example is the the expected result. Maybe you are intereseted in the round() function which allows to round to a certain precision?

Sign up to request clarification or add additional context in comments.

2 Comments

Yes I am aware of round() but problem is I am getting random number and I want to handle it accordingly.
What do you mean by "handle it accordingly?" round($_, 1) will drop the decimal if it would be 0 by number_format.
1

You can try something like this

<?php
$number = 12312;
echo is_int($number) ? $number : number_format($number,"1");
?>

Comments

0

If you don't want the extra decimal place, use <?php echo number_format(12312, 0);?>

The "0" represents 0 decimal places

Comments

0

simple casting it to float, usign (float), works.

e.g.

$num_1 = (float)1.0;

$num_2 = (float)1.1;

echo $num_1; echo $num_2;

output:

1

1.1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.