Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - float value with two decimal places

Is there any way in PHP to have a float value (not a string) with two decimal places if these are zeroes?

Example:

$v = 1.50

Using (float) or floatval($v) would return the number as 1.5

I get that I can use number_format() for an arbitrary precision, but that would return a string, and once I cast it to a float, I hit the same problem.

like image 657
Carlo Avatar asked Feb 12 '26 01:02

Carlo


2 Answers

Short answer is you can't. The variable (as a float) contains just the datum and 1.5 or 1.50 is just the same thing and internally it's stored as a floating point number.

You can see the value printed as 1.5 or 1.50 only when it's converted to a string, explicitly (using number_format()) or implicitly (printing directly the variable or inspecting the value in the debugger). You're supposed to use number_format() when you want to write the value as a string.

like image 99
Alessandro Avatar answered Feb 13 '26 15:02

Alessandro


This may be help you :

Example:

$foo = "105";

echo number_format((float)$foo, 2, '.', '');  // Outputs -> 105.00

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!