LoginSignup
2
0

More than 3 years have passed since last update.

【Rails】小数点以下の不要な0を削除する number_with_precision

Last updated at Posted at 2020-03-20

小数点の表示で0の場合だけなくすという仕様で困ったことはありませんか?
具体的には以下のような仕様です。

1.000 => 1
1.100 => 1.1
1.110 => 1.11

解決方法

ActionView::Helpers::NumberHelperクラスのnumber_with_precision(optionの strip_insignificant_zeros: true)を使います。

number_with_precision([数値],precision: [有効にしたい小数点桁数], strip_insignificant_zeros: true)

precisionを省略した場合、デフォルトは3です。

コードで仕様説明

スクリーンショット 2020-03-20 8.37.10.png
小数点以下の不要な0が全て切捨てられています。
画像の[6]をみていただくとわかりますがprecisionが3のため小数点第3位の数字までしか表示されていません。

スクリーンショット 2020-03-20 8.46.51.png

画像の[7]はpricisionを4にしているため小数点第4位まで表示されています。

2
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
2
0