2016-03-21 115 views
1

我想用动态浮点实现具有指定长度的不同输入数据长度的格式以供显示。例如x.xxxx, xx.xxxx, xxx.xx, xxxx.x带浮点数的格式

换句话说,

如果我有1.4,我需要1.4000

如果13.4那么我需要13.400,对于每个案件长度应该是5位数字(没有点)。

我使用

DecimalFormat df2 = new DecimalFormat("000000"); 

,但不能建立一个正确的模式。有没有解决方案? 感谢您的帮助。

+1

会发生什么情况是数字超过5位数 - 比如123456789? – Mzf

+0

@Mzf将它切成5个字符的长度。 123456789 = 12345,123.45677 = 123.45 – Gorets

+2

所以为什么不把它转换为字符串,并采取前5个字符?如果它少,那么在最后填零? – Mzf

回答

1

以下不是生产代码。它没有考虑到主导负数,也没有考虑常数的非常高的值。但我相信你可以用它作为出发点。感谢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; 
} 
+0

干得好,像魅力一样工作 – Gorets

+0

谢谢。 :-)我担心双精度表示中的不精确可能会导致意想不到的结果,比如1.4变成1.3999,但我还没有找到任何例子。也许双精度和%f格式的工作对于5位数是足够好的。 –

+0

如果您使用浮点,它可能会发生 – Gorets