[英]Format for number with floating point
I want to implement format with dynamic floating point for different length of input data in specified length for display.我想为指定长度的不同长度的输入数据实现带有动态浮点的格式以进行显示。 For example
x.xxxx, xx.xxxx, xxx.xx, xxxx.x
.例如
x.xxxx, xx.xxxx, xxx.xx, xxxx.x
。
In other words,换句话说,
if I have 1.4
, I need 1.4000
.如果我有
1.4
,我需要1.4000
。
if 13.4
then I need 13.400
, for every case length should be 5 digits (with no dot).如果
13.4
那么我需要13.400
,对于每个案例长度应该是 5 位数字(没有点)。
I'm using我正在使用
DecimalFormat df2 = new DecimalFormat("000000");
but can't build a correct pattern.但无法构建正确的模式。 Is there any solution for this?
有什么解决办法吗? Thanks for helping.
谢谢你的帮助。
The following is not production code.以下不是生产代码。 It doesn't take a leading minus into account, nor very high values of the
noDigits
constant.它没有考虑前导减号,也没有考虑非常高的
noDigits
常数值。 But I believe you can use it as a starting point.但我相信你可以把它作为一个起点。 Thanks to Mzf for inspiration.
感谢 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.