Lost data when convert float to int in php

前端 未结 4 800
执念已碎
执念已碎 2020-12-12 01:55

My code :

$baseprice=1705000/1.1;
var_dump($baseprice);
$parseprice=intval($baseprice);
var_dump($parseprice);

Result :

f         


        
相关标签:
4条回答
  • 2020-12-12 02:18

    The Solution would be as below

    $baseprice=1705000/1.1;
    
    var_dump($baseprice);
    
    $parseprice=intval(ceil($baseprice));
    
    var_dump($parseprice);
    

    output:

    float(1550000) int(1550000)

    0 讨论(0)
  • 2020-12-12 02:19

    Before float to integer round the value then you can convert to int

    $baseprice=1705000/1.1;
    
    var_dump($baseprice);
    //Before float to integer round the value then you can convert to int
    $baseprice =round($baseprice);
    
    $parseprice=intval($baseprice);
    var_dump($parseprice);
    
    0 讨论(0)
  • 2020-12-12 02:22

    Problem is when caculate the float, I still dont know why they have different like bellow

    $baseprice= 1705000/1.1 ; // 1550000
    
    var_dump( decbin( $baseprice )); 
    var_dump( decbin(1550000)); 
    

    We can fix this by

    $baseprice = round( $baseprice );
    
    0 讨论(0)
  • 2020-12-12 02:24

    You are using floating point numbers which will lose precision (see this link).

    If you are handling currency use integers and work in cents, pence, pfennigs, or whatever. Convert to a currency format just before display.

    0 讨论(0)
提交回复
热议问题