-3

have this numbers

0.0123999999
0.00001239999999

need to get rounding result counted from first non-zero digits

0.0124
0.0000124

and to be able to set number of non-zero digits to round, as "3" in above

but if integers exists

1.01239999 - should become 1.012

A.Kotov
  • 13
  • 2
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. – Kermit Aug 01 '14 at 19:26
  • maybe use the round() function – GeekByDesign Aug 01 '14 at 19:29
  • Thanks for sharing your needs with us! – Jack M. Aug 01 '14 at 19:33
  • was looking not an hour for solution - found only this http://stackoverflow.com/questions/16697190/round-php-decimal-value-to-second-digit-after-last-0?rq=1 - not helps exatly – A.Kotov Aug 01 '14 at 19:39

1 Answers1

2

Try this:

<?php

$number = 0.0123999999;
$numberString = number_format($number, 30, ".", "");

// for loop to count the zeros
$n = -1;
for($i = 0; $i < strlen($numberString); $i++) {
    if ($numberString[$i] == "0") $n++;
    elseif ($numberString[$i] != ".") break;
}

// rounding with the precision of 3 + the amount of zeros
$precision = 3;
echo number_format(round($number, $n + $precision), $n + $precision, ".", "");

?>
Friedrich
  • 2,211
  • 20
  • 42
  • Thank you, quiet short solution. But only does not work when zeros 5 and more. $numberString becomes in exp format. – A.Kotov Aug 01 '14 at 19:53
  • tried to put $numberString = sprintf('%f', $number); but it automaticaly rounds to 0.000001 – A.Kotov Aug 01 '14 at 20:33
  • trying to wark this out – Friedrich Aug 01 '14 at 20:57
  • now it is working properly, even for very small numbers – Friedrich Aug 01 '14 at 21:05
  • you give me very small time )) - my idea was the same - if ($number < 0.0001){$number = number_format($number, 12);} strange that $number = (double)$number; did not work out – A.Kotov Aug 01 '14 at 21:22
  • your last edit works absolutely perfect - Thank You. – A.Kotov Aug 01 '14 at 21:29
  • as you are new to stackoverflow, it would be nice to mark my answer as the accepted one, thanks;) – Friedrich Aug 01 '14 at 21:33
  • one small improvement could be done. - to throw away extra zeros from right. now $number = 0.00000001 gives 0.0000000100. i think is better to make 0.00000001 – A.Kotov Aug 02 '14 at 00:12
  • some times with high value of $zeros > 15 in number_format() - function not working properly. 0.0123 - could become 0.012299999999999999 - and breaks everything - same for first code – A.Kotov Aug 02 '14 at 00:23