Helio Soares Junior
Helio Soares Junior

Reputation: 447

How to round BigDecimal to return two decimal

I need to return BigDecimal in this format (%.##) For example i have this floating number

3.2->3.20
6.2->6.20
112.0->112.00

I'm trying this

BigDecimal precoDecial = new BigDecimal(preco);
precoDecial.setScale(2, BigDecimal.ROUND_HALF_UP);

But it is not working for me; this returns:

for:
3.2->3.2000000476837158203125
6.2->6.2

My log with the code reference enter image description here

Upvotes: 2

Views: 1276

Answers (1)

SmashCode
SmashCode

Reputation: 761

BigDecimal precoDecial = new BigDecimal(1.0);
        precoDecial = precoDecial.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println(precoDecial);

I tried this in my IDE it worked better give it a try hope my work may solve your problem

output

if 1-->1.00
if 1.0-->1.00
if 1.00000000-->1.00

Upvotes: 1

Related Questions