Java Decimal Format - as much precision as given

前端 未结 2 852
难免孤独
难免孤独 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.

提交回复
热议问题