java中四舍五入后并保留兩位小數(shù)的方法(以double為例)
1.0 String.format打印
數(shù)字格式化說明的格式:
%[argument number][flags][width][.precision]type
argument number:若參數(shù)大于1癌别,指定哪一個担敌;
flags:符號瓦哎,如(+砸脊、-焕妙、;践剂、.);
width:最小字符數(shù)陨瘩;
.precision:精確度腕够;
type:類型,如f:浮點舌劳。
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
//直接輸出結(jié)果
System.out.println(String.format("%.2f", d))帚湘;
//輸出結(jié)果:3.14
}
}
String.format 返回的是String, 若是要數(shù)據(jù)轉(zhuǎn)換為Double
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
DecimalFormat df = new DecimalFormat("#.##");
Double get_double = Double.parseDouble(String.format("%.2f", d));
System.out.println(get_double);
}
}
2.0 DecimalFormat轉(zhuǎn)換
DecimalFormat是NumberFormat的一個具體子類,用于格式化十進(jìn)制數(shù)字甚淡。符號含義:
0(代表一個數(shù)字大诸,如果不存在顯示0)
符號#(代表一個或多個數(shù)字,如果不存在則顯示為空)
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(d));
}
}
df.format(d) 返回的是String, 若是要數(shù)據(jù)轉(zhuǎn)換為Double
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
DecimalFormat df = new DecimalFormat("#.##");
Double get_double = Double.parseDouble(df.format(d));
System.out.println(get_double);
}
}
3.0 BigDecimal.setScale()
此方法用于格式化小數(shù)點贯卦。
BigDecimal.ROUND_HALF_UP表示四舍五入资柔,setScale(2)表示保留兩位小數(shù)。
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
BigDecimal bd = new BigDecimal(d);
BigDecimal bd2 = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(bd2);
}
}
數(shù)據(jù)轉(zhuǎn)換
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
BigDecimal bd = new BigDecimal(d);
BigDecimal bd2 = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
Double get_double=Double.parseDouble(bd2.toString());
System.out.println(get_double);
}
}
4.0 用Math.round()
將數(shù)乘以100后四舍五入撵割,再除以100.0
注:java中Math.round()是四舍五入取整贿堰,并不能設(shè)置保留幾位小數(shù)。
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
Double get_double = (double) ((Math.round(d * 100)) / 100.0);
System.out.println(get_double);
}
}
作者:AmorFatiYJ
鏈接:http://www.reibang.com/p/04b998c2b2eb
來源:簡書
著作權(quán)歸作者所有睁枕。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán)官边,非商業(yè)轉(zhuǎn)載請注明出處沸手。