1、使用String.format()方法:
public static void stringFormatdecimalFormatKeepTwoDecimalPlaces(){
double number = 3.1415926;
String result = String.format("%.2f", number);
System.out.println(result);
}
輸出:3.14
2、BigDecimal保留兩位小數(shù)
import java.math.BigDecimal;
public static void bigdecimalKeepTwoDecimalPlaces(){
double number = 3.1415926;
BigDecimal decimal = new BigDecimal(number);
BigDecimal rounded = decimal.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(rounded);
}
輸出:3.14
3、使用DecimalFormat類:
public static void decimalFormatKeepTwoDecimalPlaces(){
double number = 3.1415926;
DecimalFormat decimalFormat = new DecimalFormat("#.00");
String result = decimalFormat.format(number);
System.out.println(result);
}
輸出:3.14文章來源:http://www.zghlxwxcb.cn/news/detail-756400.html
這些方法中,DecimalFormat類和String.format()方法可以直接將數(shù)字格式化為保留兩位小數(shù)的字符串。而使用BigDecimal類可以對數(shù)字進行精確的四舍五入操作。
文章來源地址http://www.zghlxwxcb.cn/news/detail-756400.html
到了這里,關于java保留兩位小數(shù)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!