Gorets
Gorets

Reputation: 2442

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.

In other words,

if I have 1.4, I need 1.4000.

if 13.4 then I need 13.400, for every case length should be 5 digits (with no dot).

I'm using

DecimalFormat df2 = new DecimalFormat("000000");

but can't build a correct pattern. Is there any solution for this? Thanks for helping.

Upvotes: 1

Views: 391

Answers (1)

Anonymous
Anonymous

Reputation: 86140

The following is not production code. It doesn’t take a leading minus into account, nor very high values of the noDigits constant. But I believe you can use it as a starting point. Thanks to Mzf for inspiration.

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;
}

Upvotes: 1

Related Questions