Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP float with 2 decimal places: .00

Tags:

php

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?

like image 827
StackOverflowNewbie Avatar asked Oct 03 '12 10:10

StackOverflowNewbie


People also ask

How can I limit float to 2 decimal places in PHP?

The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function.

How can I set 2 decimal places in PHP?

$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.

How do you make a float with 2 decimals?

format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.

Is float 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.


2 Answers

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); 
like image 193
Denys Séguret Avatar answered Oct 03 '22 03:10

Denys Séguret


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.


JSON output modification

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} 
like image 37
Tim B. Avatar answered Oct 03 '22 03:10

Tim B.