May be I might be blind or silly, but look at my function:
function max_min_twenty($value) { if ((int)$value == 0) { return "0"; } else { $percent_val = ((int)$value / 100) * 20; $maxvalue = (int)$value + $percent_val; $minvalue = (int)$value - $percent_val; $returnvalue = round($minvalue)."-".round($maxvalue); return $returnvalue; } } Seems that this is really easy! It works like it should, but if my $value is 1500000 it gives me back 1,2E+6 for $minvalue - It does well if I choose a different number or if I change the percent to 19 or 21. Whats that?
Its running on PHP Version 5.2.4-2ubuntu5.27
03 Answers
Format the number explicitly as an integer? round returns a float and so I believe the default formatting is "getting confused" or "hitting an edge case" and reverts to displaying scientific notation. (I can't trigger the problem on ideone - it might be specific to a particular PHP version/environment - but the symptoms fit.)
Try sprintf:
return sprintf("%d-%d", $minvalue, $maxvalue); (I removed round as the %d forces the arguments to be treated as integers; however, there might be subtle differences in the rounding rules .. I don't know.)
try to use number_format
function max_min_twenty($value) { if ((int)$value == 0) { return "0"; } else { $percent_val = ((int)$value / 100) * 20; $maxvalue = (int)$value + $percent_val; $minvalue = (int)$value - $percent_val; $returnvalue = number_format(round($minvalue),"0","-","")."- ".number_format(round($maxvalue),"0","-",""); echo $returnvalue; } } it changed scientific notation to standard form.
You are seeing a bugged behavior in older versions of PHP. This was bug #43053 that was resolved in PHP 5.3.0.
Take, for example, this code:
for ($i = 1000000; $i < 2000000; $i += 100000) echo round($i) . "--\n"; On PHP 5.2.6 and lower, it produces the following (sample; can't guarantee CodePad will always be on old PHP):
1000000-- 1100000-- 1.2E+6-- 1300000-- 1.4E+6-- 1500000-- 1600000-- 1.7E+6-- 1800000-- 1.9E+6-- On PHP 5.3.0 and up, though, the correct behavior can be seen:
1000000-- 1100000-- 1200000-- 1300000-- 1400000-- 1500000-- 1600000-- 1700000-- 1800000-- 1900000-- This can be fixed by upgrading PHP or by avoiding round(), as @user2246674 suggests in his answer.