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 5 years have passed since last update.

Play2のビューでBigDecimalをいい感じに出力したかった

Posted at

BigDecimalのsetScale(int newScale, RoundingMode roundingMode)でいい具合にやりたいと試行錯誤しましたが、0だけ切り捨てるような丸めはありません。
いや、RoundingMode.UNNECESSARY渡せばいいんですが、ビューでやったりすると0がついてない場合にArithmeticExceptionで死んでしまいます。

例のごとく検索しましたが、すっきりする解決法が見つかりません。
以下なら期待する結果を得ることはできそうです。1

0を表示させたくない。 - Java Solution - @IT
http://www.atmarkit.co.jp/bbs/phpBB/viewtopic.php?topic=7653&forum=12

次のようなトリミングメソッドを書きます。
例外処理に依存したコードなんですが、
JDC Tech Tipsで紹介されてるのでフォーマルなんでしょう。

とのことで、以下のコードが紹介されています。

static BigDecimal trim(BigDecimal n) {
    try {
        while (true) {
            n = n.setScale(n.scale()-1);
        }
    } catch (ArithmeticException e) {
        // no more trailing zeroes so exit.
    }
    return n;
}

そんな、ばかな……。
こんなの頻発するんだから何かありそうなものですけど。

  1. TechTipsがデッドリンクになってますが、BigDecimalで表される数値の書式設定が同じ内容と思われます。

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?