19

Simple maths:

  $a=$b/$c; echo $a;

if $b equals to 123.00 and $c equals to 1 then $a becomes 123.

If $b is 123.50, $c is 1, $a is 123.50. But in the former case , I want $a to be 123.00.

It is possible to test whether $a has any non-zero fraction part or not, and then add the trailing zeros as necessary.

But I am looking for php functions to do the same thing. Possible?

EDIT :

What if I do not want the commas from number_format there ?

4

3 Answers 3

40

Use sprintf("%0.2f",$a);. docs

3
  • @nickb how is that correct - codepad.viper-7.com/naZQVN ? Or I'm not seeing somth? Jul 16, 2012 at 19:27
  • @ZoltanToth - From the OP: But in the former case , I want $a to be 123.00.
    – nickb
    Jul 16, 2012 at 19:34
  • @nickb Sorry, my bad. I thought in the 1st case the OP wants just 123, and in the 2nd - 123.00 (floored with decimals) Jul 16, 2012 at 19:37
14

Use the number_format function. If you don't want comma separators, set all four parameters of the function like so (the thousands separator is the fourth parameter):

$number = number_format(1234, 2, '.', '');
2
  • The link to the function number_format() would be more helpful.
    – Lion
    Jul 16, 2012 at 19:07
  • @Palladium, recognized as useful Jul 16, 2012 at 19:49
4

Yup, using https://www.php.net/manual/en/function.number-format.php function like this:

$a = 123;
$answer = number_format($a,"2");
echo $answer;
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.