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?

gtilflm
  • 1,389
  • 1
  • 21
  • 51

3 Answers3

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);
Community
  • 1
  • 1
Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
  • 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. – gtilflm Sep 28 '13 at 20:16
  • This does work, but it gives me values like 7.5 instead of 7.50. Any suggestions on that? – socca1157 Mar 01 '15 at 23:19
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;
}
gtilflm
  • 1,389
  • 1
  • 21
  • 51
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

socca1157
  • 365
  • 3
  • 17