0

I am having a problem with php conversion from string to float

In some cases, if I do:

floatval("8.80")

I get:

8.800000000000001

I have struggled with round(x,1), number_format, etc, but to no avail

What am I getting wrong here?

Kira
  • 25
  • 3

3 Answers3

1

By using number_format will help to resolve your issue

<?php
    $number = 8.800000000000001;
    $precision = 1;
    $number = intval($number * ($p = pow(10, $precision))) / $p;
    echo number_format((float) $number, $precision, '.', ''); 
?>

enter image description here

MK Vimalan
  • 1,213
  • 14
  • 28
0

I have same issuer, cast in string with number_format ou bcmath library work for display. But if you do a calcul, same problem.

<?php
    $number = 8.800000000000001;
    $precision = 1;
    $number = intval($number * ($p = pow(10, $precision))) / $p;
    echo (float)number_format((float) $number, $precision, '.', '');
?>

This give the same bad result

Thomas
  • 19
  • 2
  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/34140595) – Eyad Mohammed Osama Apr 04 '23 at 11:27
0

I found the solution. You need to set the "precision" PHP variable ("serialize_precision" pour php8) to 14 or more

ini_set("precision",17);

or

ini_set("serialize_precision",17);
Thomas
  • 19
  • 2