Shobit
Shobit

Reputation: 794

How do you truncate extra decimals from BigDecimal

I'm building a service that uses a currency converter and forwards the BigDecimal amount to another service. Sometimes, the conversion rate makes it so that the converted amount has close to 34 decimal places, which the downstream service does not accept.

Is there a way to simply truncate (not round) the BigDecimal. So, for example, if the converted amount is 1.23456789 I want neither 1.24, nor 1.3, nor 1.20, or anything of that sort. I simply want to get rid of the decimals that appear after 4. So what I want is 1.23.

I saw a lot of questions on SO related to this, but they all rounded the BigDecimal in some way.

Thanks!

Upvotes: 2

Views: 7067

Answers (4)

Leo
Leo

Reputation: 6570

you could try treating it like a string

System.out.println(new DecimalFormat("#0.##").format(new BigDecimal("1.23456789")));

Upvotes: 1

Vinayak Pingale
Vinayak Pingale

Reputation: 1315

BigDecimal also provides Rounding Modes. Try this

BigDecimal bd = new BigDecimal(2.2964556655);
System.out.println(bd.setScale(2,BigDecimal.ROUND_DOWN));

Upvotes: 0

StoopidDonut
StoopidDonut

Reputation: 8617

RoundingMode.DOWN effectively truncates your decimal values:

Javadoc says:

Rounding mode to round towards zero. Never increments the digit prior to a discarded fraction (i.e., truncates). Note that this rounding mode never increases the magnitude of the calculated value.

BigDecimal dec = new BigDecimal(10.2384235254634623524);
System.out.println(dec.setScale(2, RoundingMode.DOWN));

Will give:

10.23

Upvotes: 7

Qiang Jin
Qiang Jin

Reputation: 4467

BigDecimal provides RoundingMode, which you need here is RoundingMode.FLOOR,

System.out.println(new BigDecimal("1.234567").setScale(2, RoundingMode.FLOOR)); // 1.23
System.out.println(new BigDecimal("1.236567").setScale(2, RoundingMode.FLOOR)); // 1.23

Upvotes: 4

Related Questions