PHP float with 2 decimal places: .00

后端 未结 11 1029
野性不改
野性不改 2020-12-08 06:34

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?

相关标签:
11条回答
  • 2020-12-08 06:47

    You can use round function

    round("10.221",2);
    

    Will return 10.22

    0 讨论(0)
  • 2020-12-08 06:50

    0.00 is actually 0. If you need to have the 0.00 when you echo, simply use number_format this way:

    number_format($number, 2);
    
    0 讨论(0)
  • 2020-12-08 06:55

    You can use floatval()

    floatval()

    0 讨论(0)
  • 2020-12-08 06:56

    A float isn'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);
    
    0 讨论(0)
  • 2020-12-08 06:56

    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}
    
    0 讨论(0)
  • 2020-12-08 07:04

    you can try this,it will work for you

    number_format(0.00, 2)
    
    0 讨论(0)
提交回复
热议问题