简体   繁体   中英

how to round DecimalFormat in java (android)

I want to round

0.005 to 0.01

im using this code

DecimalFormat df = new DecimalFormat("0.00");

but the answer keeps getting 0.00 I want only 2 digits on the right with rounding if possible anybody has an idea?

You should add the RoundingMode for the DecimalFormat

double d = 0.005;
DecimalFormat df = new DecimalFormat("0.00");
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(df.format(d)); //0.01

For rounding use BigDecimal

BigDecimal decimal = new BigDecimal(number);
decimal = decimal.setScale(2, RoundingMode.HALF_UP);
String result = decimal.toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM