带浮点数的格式

时间:2016-03-21 11:08:26

标签: java string floating-point double string-formatting

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

换句话说,

如果我有1.4,我需要1.4000

如果13.4那么我需要13.400,因为每个案例的长度应该是5位数(没有点)。

我正在使用

DecimalFormat df2 = new DecimalFormat("000000");

但无法构建正确的模式。这有什么解决方案吗? 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

以下不是生产代码。它不考虑前导减号,也不考虑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;
}
相关问题