無意中發現的怪現象

來源:互聯網
上載者:User

今天寫代碼進行測試的時候發現個怪現象,賣個關子,大家先看看下面這幾段代碼都輸出什麼,看你能全做對嗎:)

//代碼1<br />$s = 0.4;<br />$x = intval($s);<br />$y = intval(($s - $x) * 10);<br />var_dump($x);<br />var_dump($y);<br />//代碼2<br />$s = 1.4;<br />$x = intval($s);<br />$y = intval(($s - $x) * 10);<br />var_dump($x);<br />var_dump($y);<br />//代碼3<br />$s = 1.5;<br />$x = intval($s);<br />$y = intval(($s - $x) * 10);<br />var_dump($x);<br />var_dump($y);

代碼很簡單,相信你也有了自己的答案。下面運行下看看結果吧:
int(0) int(4)
int(1) int(3)
int(1) int(5)
哈哈,是不是第二組錯了呢?第二個按理說應該是int(4)呀。
看到這個結果,讓我直接想到了應該和java中的那個2.00-1.10等於0.8999999999問題類似。但該怎麼解決呢?

經論壇中d9tx的點撥,終於明白,PHP中精密的運算需使用BC math高精度數學函數。把代碼修改為下面就OK了~

$s = 1.4;<br />$x = intval($s);<br />$y = intval(bcmul(bcsub($s,$x, 1),10));<br />var_dump($x);<br />var_dump($y);

備忘:BC math高精度數學函數(具體用法大家查手冊吧)

bcadd — Add two arbitrary precision numbers
bccomp — Compare two arbitrary precision numbers
bcdiv — Divide two arbitrary precision numbers
bcmod — Get modulus of an arbitrary precision number
bcmul — Multiply two arbitrary precision number
bcpow — Raise an arbitrary precision number to another
bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
bcscale — Set default scale parameter for all bc math functions
bcsqrt — Get the square root of an arbitrary precision number
bcsub — Subtract one arbitrary precision number from another

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.