1

number_format stupidly rounds numbers by default. Is there just a simple way to turn off the rounding? I'm working with randomly generated numbers, and I could get things like...

42533 * .003 = 127.599 or,
42533 * .03 = 1275.99 or,
42533 * .3 = 12759.9

I need number_format (or something else) to express the result in traditional U.S. format (with a comma separating the thousands) and not round the decimal.

Any ideas?

2
  • Can you please add the expected result, too? Commented Sep 28, 2013 at 20:09
  • @AmalMurali: I would want 12759.9 to be displayed as 12,759.9. Commented Sep 28, 2013 at 20:11

3 Answers 3

1

The second argument of number_format is the number of decimals in the number. The easiest way to find that out is probably to treat it as a string (as per this question). Traditional US format is default behaviour, so you don't need to specify remaining arguments.

$num_decimals = strlen(substr(strrchr($number, "."), 1));
$formatted_number = number_format($number, $num_decimals);
Sign up to request clarification or add additional context in comments.

2 Comments

Seems to be working... Thanks. Even though it's RETARDED that we even have to go through this. It's stupefying as to why you can't turn off the rounding of number_format.
This does work, but it gives me values like 7.5 instead of 7.50. Any suggestions on that?
0

If anyone's interested in this, I've written a little function to get around this problem.

With credit to Joel Hinz above, I came up with...

function number_format_with_decimals($value, $round_to){
    //$value is the decimal number you want to show with number_format.
    //$round_to is the deicimal place value you want to round to.

    $round_to_decimals = strlen(substr(strrchr($value, "."), $round_to));
    $ans = number_format($value, $round_to);

    return $ans;
}

Comments

0

I tried these solutions, but what ended up being my answer was this:

$output=money_format('%!i', $value);

This gives you something like 3,234.90 instead of 3,234 or 3,234.9

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.