Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a BigDecimal to a 2-decimal-place string?

Tags:

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) 
like image 715
Saqib Ali Avatar asked Jul 23 '14 16:07

Saqib Ali


People also ask

How do you convert a string to two decimal places?

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.

How do you do 2 decimal places in Java?

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 (%).

Does BigDecimal have decimal places?

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

How about combining BigDecimal#truncate and String#%? :

"%.2f" % BigDecimal("7.1762").truncate(2) # => "7.17" "%.2f" % BigDecimal("4.2").truncate(2) # => "4.20" 
like image 159
falsetru Avatar answered Sep 30 '22 19:09

falsetru