在java中:我在變量(例如用戶選擇)中有一些數字和一些所需的小數位數, ,我需要打印它。在java中基於用戶變量的小數位格式化
myNumber = 3.987654;
numberOfDecimalPlaces = 4;
我不想做這樣
System.out.printf("%.4f", myNumber);
,但我需要使用可變numberOfDecimalPlaces
代替。
非常感謝
在java中:我在變量(例如用戶選擇)中有一些數字和一些所需的小數位數, ,我需要打印它。在java中基於用戶變量的小數位格式化
myNumber = 3.987654;
numberOfDecimalPlaces = 4;
我不想做這樣
System.out.printf("%.4f", myNumber);
,但我需要使用可變numberOfDecimalPlaces
代替。
非常感謝
只需創建格式字符串中使用numberOfDecimalPlaces
:
System.out.printf("%." + numberOfDecimalPlaces + 'f', myNumber);
@VivekSingh這就是他想要做的。他說他不希望它使用靜態數字,但希望它動態變化。這完全適用。 +1 –
@UmaKanth謝謝,這也是我的理解 – wero
我去這個aswell,即使我發佈NumberFormat示例 –
你可以用這個方法嘗試:
//value is your input number and places for required decimal places
public static double function(double value, int places) {
if (places < 0) {
throw new IllegalArgumentException();
}
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp/factor;
}
我可以知道爲什麼? –
不明白爲什麼@ wero不是一個好的答案,但是如果你不喜歡使用System.out。也許這個..
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(numberOfDecimalPlaces);
nf.setMinimumFractionDigits(numberOfDecimalPlaces);
String toPrint = nf.format(myNumber);
的【如何把一個數字在Javañ小數]可能的複製(http://stackoverflow.com/questions/153724/how-to-round-a-number-to -n-decimal-places-in-java) – InbetweenWeekends