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".
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With