简体   繁体   中英

Is it possible to specify exact number of fractional digits in DecimalFormat parsing?

I'm using DecimalFormat to parse strings representing decimal numbers. What I'd like to have is to a parsing function which checks the exact number of fractional digits in strings. In details, I want to check that the string has exactly two fractional digits (eg, "1.10" is valid, "1.1" is not valid).

Is it possible to have such behavior with DecimalFormat ? The instance built with following method doesn't work.

private static DecimalFormat decimalFormat() {
    final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
    decimalFormatSymbols.setDecimalSeparator('.');
    final DecimalFormat decimalFormat = new DecimalFormat("#0.00", decimalFormatSymbols);
    decimalFormat.setMinimumFractionDigits(2);
    decimalFormat.setParseBigDecimal(true);
    return decimalFormat;
}

Any suggestions?

Here is the documentation on setMinimumIntegerDigits : https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html#setMinimumIntegerDigits-int-

newValue - the minimum number of integer digits to be shown; [...].

As far as I can understand, this does not act as a requirement, only as a format for the output.

Looking through the available functions for DecimalFormat , I can't see anything that would give you the number of fraction digits.

BUT, since you are using setParseBigDecimal(true) , parsing a string would then give you a BigDecimal which gives you access to the precision function : https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#precision--

So what I suggest if you absolutely want to check the result of the parse (and not the string itself) for the correct number of digits is :

  • set the minimum fraction digits to 0
  • take the string
  • parse it in BigDecimal
  • use the BigDecima::precision function to check if the number of digits is correct.

Hope this helps.

It sounds like you're trying to validate a condition rather than convert a string to a given format. You can use regular expressions to do this. Here's an example method that I believe does what you want

public boolean hasTwoFractionalDigits(String text) {
    return Pattern.compile("^\\d+\\.\\d\\d$").matcher(text).find();
}

This will return true for "10.33" but false for "10.3". If this doesn't answer your question let me know.

if price has decimal(.) then decimal(.) always have digit as prefix and suffix both. ie ' 0.0 ' integer price is acceptable. max 2 fractional digit.

5, 5.0, 5.00 Accept 0, 0.0, 0.00 5. .5, 5.000, ., .0, .00, .000, 0. String = Error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM