0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PHPのfloor関数で誤差が出たのでBC Math 関数で対応した話

Posted at

環境

  • php:8.1

対象

  • floor関数を使って誤差が出てしまった人

原因

以下に記載されていますが、浮動小数点の精度が計算結果に誤差を生じさせるようです。
https://www.php.net/manual/ja/language.types.float.php

Controller.php
$result =floor((0.1+0.7)*10);

echo $result; // 7になる

対応

BC Math 関数を使用して対応します。

Controller.php
$number = (0.1+0.7)*10;  

$result = (int)(bcdiv((string)$number, '1', 0));

echo $result;  // 正しい結果の8になる
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?