so I am trying to achieve this
I have decimal 1.00 Which when i convert to float becomes 1.0. So my question is how can i save the last zero and at the same time to be float not a string if i use number_format(1.0,2) it becomes "1.00" Which is string but i need to be decimal with the last zero. This is what i tried so far
<?php
$decimal = "1.0";
$decimalToFloat = floatval($decimal) // It becomes 1.0
$decimalToFloat = number_format($decimal,2) // It becomes "1.00" !!! String not a float !!!
// The result which i want is 1.00 not "1.00"
Let me start by saying that this is an XY problem, as you don't need to convert from a string to an integer in PHP, as PHP will coerce the type for you automatically.
In addition to this, there is no need to specify the number of places on a decimal, as 1 is exactly equal to 1.0, and 1.0 is exactly equal to 1.00. In fact, forcibly casting the string showcases that PHP will automatically trim the decimal places:
$decimal = "1.0";
echo number_format((float)$decimal, 2, '.', ''); // "1.00" (string)
echo (int)number_format((float)$decimal, 2, '.', ''); // 1 (int)
echo (float)number_format((float)$decimal, 2, '.', ''); // 1 (float)
It is impossible to showcase an int or float with decimal places comprised purely of zeros in PHP. Though you do not need to do this; you can simply use the whole numbers instead:
echo 1 + 1.01; // 2.01 (float)
Hope this helps! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With