0
1

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.

四捨五入をしたいときはROUND関数を使うべきではない

Last updated at Posted at 2024-02-26

ROUND関数は四捨五入ではない

結論:

mysqlで四捨五入したいときはTRUNCATE関数を使用する。

発生した事象:

四捨五入をしたいと思い、round(1.05, 1)を行なった所、結果が1.0になってしまった。

解決策:

TRUNCATE(1.05+0.5, 1)としたところ、結果が1.1となり想定通りの四捨五入となった。
1.05に0.5を足すと。1.1になり「1」を指定しているため、小数点第二位が切り落とされ、そのまま1.1になる。

仮に、TRUNCATE(1.04+0.5, 1)とした場合は、1.0になる。
1.04に0.5を足すと、1.09となり「1」を指定しているため、小数点第二位が切り落とされ、1.0になる。
→とりあえず0.5足して、指定したそこの桁を切り落とすイメージ。

sql
TRUNCATE([数値]+0.5, [四捨五入したい桁])

参考サイト
https://www.softel.co.jp/blogs/tech/archives/2570
https://www.softel.co.jp/blogs/tech/archives/1420

0
1
3

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?