I want to convert a BigDecimal object to a currency value to two decimal places. I don't want any rounding. How can I do it?
None of the following approaches worked:
v = BigDecimal("7.1762") w = BigDecimal("4.2") v.to_s('2F') # => "7.17 62" v.to_s('F') # => "7.1762" v.to_s('%0.2F') # => "0.71762E1" v.to_s('%0.2f') # => "0.71762E1" v.truncate(2).to_s('F') # => "7.17" # This one looks like it worked w.truncate(2).to_s('F') # => "4.2" # But it doesn't pad with the trailing zero(es)
Round(temp, 2); Alternatively, if you want the result as a string, just parse it and format it to two decimal places: double temp = Double.
The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
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.
How about combining BigDecimal#truncate
and String#%
? :
"%.2f" % BigDecimal("7.1762").truncate(2) # => "7.17" "%.2f" % BigDecimal("4.2").truncate(2) # => "4.20"
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