PHP float with 2 decimal places: .00

后端 未结 11 1034
野性不改
野性不改 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: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}
    

提交回复
热议问题