Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a BigDecimal to only show as many decimal digits as needed?

I have a BigDecimal that has either 0, 1 or 2 decimal digits (I'm calling round(2) on it). I want to display it in a view in such a way that it'll only show as many decimal digits as needed. In other words:

 7.0 -> "7"
 7.5 -> "7.5"
 7.67 -> "7.67"

How do I achieve this? So far, it's showing "7.0" instead of "7".

like image 578
Daniel Magliola Avatar asked Sep 11 '12 20:09

Daniel Magliola


People also ask

How do I limit decimal places in Java?

We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places. For DecimalFormat , the default rounding mode is RoundingMode. HALF_EVEN , and we can use setRoundingMode(RoundingMode) to set a specified rounding mode.

How do I stop rounding in BigDecimal?

math. BigDecimal. round(MathContext m) is an inbuilt method in Java that returns a BigDecimal value rounded according to the MathContext settings. If the precision setting is 0 then no rounding takes place.

Does BigDecimal have decimal places?

Class BigDecimal. Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point.


1 Answers

For your views, look at the methods from the NumberHelper, in particular the number_with_precision, http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision

Particularly, you want the strip_insignificant_zeros option.

like image 137
MurifoX Avatar answered Oct 14 '22 02:10

MurifoX