[英]Freemarker - Is there a way to format an integer as a floating point number?
[英]Format for number with floating point
我想為指定長度的不同長度的輸入數據實現帶有動態浮點的格式以進行顯示。 例如x.xxxx, xx.xxxx, xxx.xx, xxxx.x
。
換句話說,
如果我有1.4
,我需要1.4000
。
如果13.4
那么我需要13.400
,對於每個案例長度應該是 5 位數字(沒有點)。
我正在使用
DecimalFormat df2 = new DecimalFormat("000000");
但無法構建正確的模式。 有什么解決辦法嗎? 謝謝你的幫助。
以下不是生產代碼。 它沒有考慮前導減號,也沒有考慮非常高的noDigits
常數值。 但我相信你可以把它作為一個起點。 感謝 Mzf 的啟發。
final static int noDigits = 5;
public static String myFormat(double d) {
if (d < 0) {
throw new IllegalArgumentException("This does not work with a negative number " + d);
}
String asString = String.format(Locale.US, "%f", d);
int targetLength = noDigits;
int dotIx = asString.indexOf('.');
if (dotIx >= 0 && dotIx < noDigits) {
// include dot in result
targetLength++;
}
if (asString.length() < targetLength) { // too short
return asString + "0000000000000000000000".substring(asString.length(), targetLength);
} else if (asString.length() > targetLength) { // too long
return asString.substring(0, targetLength);
}
// correct length
return asString;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.