Java Decimal Format - as much precision as given

前端 未结 2 834
难免孤独
难免孤独 2021-01-18 21:53

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).

相关标签:
2条回答
  • 2021-01-18 22:31

    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.

    0 讨论(0)
  • 2021-01-18 22:40

    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.

    0 讨论(0)
提交回复
热议问题