Gilberto T.
Gilberto T.

Reputation: 378

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 (e.g., "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?

Upvotes: 1

Views: 2038

Answers (3)

Shakti Pravesh
Shakti Pravesh

Reputation: 91

if price has decimal(.) then decimal(.) always have digit as prefix and suffix both. i.e '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

Upvotes: 0

Olivier Samson
Olivier Samson

Reputation: 703

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.

Upvotes: 1

Procyk
Procyk

Reputation: 1

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.

Upvotes: 0

Related Questions