0

I have issue with my conversion from string to double/float. It is so strange when I run application on my local machine it working great. But when I run it on Hosting4Real hosting it making so much decimals. E.g. code

$number = "5.30";
$convNum  = (float)$number;
echo $convNum;

output

5.29999999999999982236431605997495353221893310546875

I have tried number_format() and it works but it's converting to string, I have tried with round and nothing happens. It's so strange and logic wired that I can't understand why it doesn't work.

Patrick Yoder
  • 1,065
  • 4
  • 14
  • 19
Pulsar
  • 35
  • 7
  • How did you try with `round()`? – AbraCadaver Jun 29 '21 at 20:18
  • 1
    Floats are notoriously unreliable due to rounding precision. There’s [a guide](https://floating-point-gui.de/) that explains why this happens. – rickdenhaan Jun 29 '21 at 20:19
  • "unitNetPrice" => round((double)data_get($arg, 'unik.price', 0),2), – Pulsar Jun 29 '21 at 20:21
  • Yes but how if it works great on my local machine with standard, how can it be different on hosting server. And how to make it double because it is important API post because they only accept decimal. – Pulsar Jun 29 '21 at 20:23
  • please check if this help you or not -https://stackoverflow.com/a/24018780/3200792 – Dr Manish Lataa-Manohar Joshi Jun 29 '21 at 20:27
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Tangentially Perpendicular Jun 29 '21 at 21:06
  • I would suggest not using floats for representing money unless you like losing a lot of pennies. – Sammitch Jun 29 '21 at 23:38
  • As for the reason why it looks like that, see @TangentiallyPerpendicular's link, and [this example](https://3v4l.org/Hi9Ma) illustrating the effect of your provider's high setting for [`precision`](https://www.php.net/manual/en/ini.core.php#ini.precision). – Sammitch Jun 29 '21 at 23:42

1 Answers1

1

Instead of casting, I'd use floatval().

$number = "5.30";
$convNum = floatval($number);
echo $convNum; // 5.3

If you're wanting to retain decimal point precision, you can use number_format() in conjunction.

$number = "5.30";
$convNum = number_format(floatval($number), 2); // 2 dp
echo $convNum; // 5.30
Reece
  • 574
  • 3
  • 10