Skip to content

Tag: bigdecimal

Big Decimal array not sorting 0 and 000.000

I was solving a java HackerRank problem in which I had to sort an array consisting decimal numbers using BigDecimal class in descending order. The solution works fine except for one case in which 0 and 000.000 comes. Now as they are equal, the problem tells us not keep them in the same order of their occurrence, but it is

Create BigDecimal from unscaled long

I’m trying to convert long 1099 to BigDecimal 10.99; This gives me 11.00: AFAIK this should work. What’s my bonehead error? Answer The error is that there’s a distinction between scale and precision. The constructor of MathContext accepts a precision, which is a total number of decimal digits on either side of the decimal point. (For example, the original BigDecimal

BigDecimal – to use new or valueOf

I came across two ways of getting BigDecimal object out of a double d. new BigDecimal(d) BigDecimal.valueOf(d) Which would be a better approach? Would valueOf create a new object? In general (not just BigDecimal), what is recommended – new or valueOf? Answer Those are two separate questions: “What should I use for BigDecimal?” and “What do I do in general?”