Java Decimal Format - as much precision as given

2019-02-23 07:31发布

I'm working with DecimalFormat, I want to be able to read and write decimals with as much precision as given (I'm converting to BigDecimal).

Essentially, I want a DecimalFormat which enforces the following pattern "\d+(\.\d+)?" i.e. "at least one digit then, optionally, a decimal separator followed by at least one digit".

I'm struggling to be able to implement this using DecimalFormat, I've tried several patterns but they seem to enforced fixed number of digits.

I'm open to alternative ways of achieving this too.

Edit:

For a little more background, I'm parsing user-supplied data in which decimals could be formatted in any way, and possibly not in the locale format. I'm hoping to let them supply a decimal format string which I can use the parse the data.

2条回答
劳资没心,怎么记你
2楼-- · 2019-02-23 07:46

Since you noted in a comment that you need Locale support:

Locale locale = //get this from somewhere else
DecimalFormat df = new DecimalFormat();
df.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));
df.setMaximumFractionDigits(Integer.MAX_VALUE);
df.setMinimumFractionDigits(1);
df.setParseBigDecimal(true);

And then parse.

查看更多
狗以群分
3楼-- · 2019-02-23 07:58

This seems to work fine:

public static void main(String[] args) throws Exception{
    DecimalFormat f = new DecimalFormat("0.#");
    f.setParseBigDecimal(true);
    f.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));// if required


    System.out.println(f.parse("1.0"));   // 1.0
    System.out.println(f.parse("1"));     // 1
    System.out.println(f.parse("1.1"));   // 1.1
    System.out.println(f.parse("1.123")); // 1.123
    System.out.println(f.parse("1."));    // 1
    System.out.println(f.parse(".01"));   // 0.01
}

Except for the last two that violate your "at least one digit" requirement. You may have to check that separately using a regex if it's really important.

查看更多
登录 后发表回答