When I do this typecasting:
(float) '0.00';
I get 0
. How do I get 0.00
and still have the data type as a float?
The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function.
$twoDecNum = sprintf('%0.2f', round($number, 2)); The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding. Show activity on this post. This will give you 2 number after decimal.
format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.
To parse a float with 2 decimal places:Use the toFixed() method to format the float to 2 decimal places. The toFixed method will return a string representation of the number formatted to 2 decimal places.
A float doesn't have 0
or 0.00
: those are different string representations of the internal (IEEE754) binary format but the float is the same.
If you want to express your float as "0.00", you need to format it in a string, using number_format :
$numberAsString = number_format($numberAsFloat, 2);
As far as i know there is no solution for PHP to fix this. All other (above and below) answers given in this thread are nonsense.
The number_format function returns a string as result as written in PHP.net's own specification.
Functions like floatval/doubleval do return integers if you give as value 3.00 .
If you do typejuggling then you will get an integer as result.
If you use round() then you will get an integer as result.
The only possible solution that i can think of is using your database for type conversion to float. MySQL for example:
SELECT CAST('3.00' AS DECIMAL) AS realFloatValue;
Execute this using an abstraction layer which returns floats instead of strings and there you go.
If you are looking for a solution to fix your JSON output to hold 2 decimals then you can probably use post-formatting like in the code below:
// PHP AJAX Controller // some code here // transform to json and then convert string to float with 2 decimals $output = array('x' => 'y', 'price' => '0.00'); $json = json_encode($output); $json = str_replace('"price":"'.$output['price'].'"', '"price":'.$output['price'].'', $json); // output to browser / client print $json; exit();
Returns to client/browser:
{"x":"y","price":0.00}
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