[英]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.