php中float轉int精度丟失的問題

今天遇到一個問題,$19.99轉換爲內部貨幣時的比例是1:100,所以乘以100,結果是1999,但是訂單信息描述中將數據轉換爲int(不確定, 因爲裏面是將含有該float數值字段的數組做json_encode處理的)時,數值變爲了1998。原來float和int在計算機的二進制存儲方式不同,參考:https://www.cnblogs.com/ClassNotFoundException/p/6198805.html

解決方法:先使用strval()轉爲字符串,再使用intval(),官方文檔推薦的方案
https://www.php.net/manual/zh/function.intval.php

<?php

   // observe the following
   echo intval( strval( -0.0001 ) ); // 0
   echo intval( strval( -0.00001 ) ); // -1

   // this is because
   echo strval( -0.0001 ); // -.0001
   echo strval( -0.00001 ); // -1.0E-5

   // thus beware when using
   function trunc2_bad( $n ) {
      return intval( strval( $n * 100 ) / 100 );
   }

   // use this instead
   function trunc2_good( $n ) {
      return intval( floatval( strval( $n * 100 )  ) / 100 );
   }

?>

Author:leedaning
本文地址:https://blog.csdn.net/leedaning/article/details/103074520

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章