[英]Java: How to format String number with tenth exponent
我有一個數字作為字符串,例如:“ 9.756088256835938E-4”,但我只能使用指定數量的字符(在這種特殊情況下為9個字符)。 所以我想要這樣的東西:“ 9.7561E-4”。 我已經嘗試過將String轉換為Double,然后使用format方法獲得較少的字符,但是我沒有正確的解決方案。
問題是我需要十個指數輸出,因為某些數字比我擁有的字符數長。 如果可能的話,顯示的數字應不包含十個指數,如果不能,則僅使用十個指數。
正確的舍入也很好。
它應該適用於負數。 (減號需要一個字符!!!)
是否可以使用格式函數定義輸出字符串的最大長度? 有任何想法嗎?
我在findind單一格式模式方面遇到了麻煩,該模式將涵蓋您描述的所有情況。 但是,我認為這是一種有效的邏輯組合:
public static void main(String[] args) throws Exception {
// 97.560883
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+1")));
// 9.756E+11
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+11")));
// 0.0009756
System.out.println(formatNum(Double.parseDouble("9.756088256835938E-4")));
// -9.8E+111
System.out.println(formatNum(Double.parseDouble("-9.756088256835938E+111")));
}
private static final int MAX_LENGTH = 9;
private static String formatNum(double number) {
String out = null;
for ( int i = 0; i < MAX_LENGTH; i++ ) {
String format = "%." + i + "G";
out = String.format(format, number);
if ( out.length() == MAX_LENGTH ) {
return out;
}
}
return out; //the best we can do
}
模式中的“ G”指示格式化程序在允許相同或更好的精度時放棄使用指數。 我們長到最大長度,並在輸出字符串為10個字符時停止。 我認為您可以對DecimalFormat
采取相同的方法,但是我對Formatter
更為熟悉。
看到Mark的示例滿足您的要求,我更新了答案以顯示DecimalFormat
實現。 我用了馬克的測試用例。 這絕對是一個較丑陋的選擇,因為沒有簡單的方法可以打開/關閉指數。 優於String.format
選項的唯一優點是它可以很好地處理非常小的數字。
public static void main(String[] args) throws Exception {
// 97.560883
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+1")));
// 9.756E+11
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+11")));
// 0.0009756
System.out.println(formatNum(Double.parseDouble("9.756088256835938E-4")));
// -9.8E+111
System.out.println(formatNum(Double.parseDouble("-9.756088256835938E+111")));
}
private static final int MAX_LENGTH = 9;
private static String formatNum(double number) {
int digitsAvailable = MAX_LENGTH - 2;
if (Math.abs(number) < Math.pow(10, digitsAvailable)
&& Math.abs(number) > Math.pow(10, -digitsAvailable)) {
String format = "0.";
double temp = number;
for (int i = 0; i < digitsAvailable; i++) {
if ((temp /= 10) < 1) {
format += "#";
}
}
return new DecimalFormat(format).format(number);
}
String format = "0.";
for (int i = 0; i < digitsAvailable; i++) {
format += "#";
}
String r = new DecimalFormat(format + "E0").format(number);
int lastLength = r.length() + 1;
while (r.length() > MAX_LENGTH && lastLength > r.length()) {
lastLength = r.length();
r = r.replaceAll("\\.?[0-9]E", "E");
}
return r;
}
這讓我想起了一個類似的問題 ,即OP只能為一個數字保留5個左右的空格,並且只想在有足夠的空格時才顯示小數。 但是要使用(k,m等)后綴代替指數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.