简体   繁体   中英

Formatting 2 decimal places in java

here's my example:

double num = 0;

num = 4/3;


System.out.println(num);

And my output is 1.0 instead of 1.3

Any suggestions?

Don't do int division since this always will result in a truncated int. Instead have your division use at least one double value.

double num = 4.0/3.0;

Then when you want to display it as a String, format the output so you can choose your decimal places:

// one way to do it
// %.3f is for a floating number with 3 digits to the right of the decimal
// %n is for new line
System.out.printf(%.3f%n, num); 

Another:
DecimalFormat decimalFormat = new DecimalFormat("0.000");
System.out.println(decimalFormat.format(num));

Write

num=(double)4/3;

It will return 1.3333 .... Then you can round off the decimals

您还应该使用 String.format(%1.2f, yourDouble) 来格式化您的小数位

Try this..

double value= 255.956666;

BigDecimal bd = new BigDecimal(value).setScale(2, RoundingMode.HALF_UP);
System.out.println("value="+bd);

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