0

I want to validate that a float or Double has minimum 5 numbers after decimal points.This is the code I have written

private boolean invalidDecimalPrecision(Double point)
{
    int decimalPrecision = BigDecimal.valueOf(point).scale();

    return !(decimalPrecision >= 5);

}

Is it good enough or do I have to handle specific case of negative scale numbers as well

Abhijeet Kushe
  • 2,477
  • 3
  • 26
  • 39
  • 3
    It's not really clear what you mean. Consider 0.1d - that isn't exactly 0.1, so the *exact* representation will have more than 5 digits after the decimal point. Would you want that to succeed or not? It's not generally useful to think about the number of decimal digits with `double`. – Jon Skeet Mar 08 '14 at 15:54
  • I mean that if a user inputs 0.2322 as input from a form I want to throw an error saying that the precision is incorrect but if the user inputs 0.23223 then it is a valid value.I store the number as a Double and not as a string.I used valueOf as JavaDocs say that it is best way to convert double to BigDecimal.Do you think that this will not server my purpose http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#valueOf(double) – Abhijeet Kushe Mar 08 '14 at 17:17
  • *Why* do you store the number as a `double`? Why not either store it as a `String` or a `BigDecimal`? Why go via `double` at all? – Jon Skeet Mar 08 '14 at 17:19
  • And what are you going to do with values which are not of exactly this form? I'm having trouble thinking of any situation where this test makes any kind of sense. What's the real task you're trying to perform? The answer may be that you don't want floating point, or even decimal, at all. – keshlam Mar 08 '14 at 17:52
  • I am going to discard those values if they are not in that form.This is used to store geo-coordinates that are entered through a form or a rest call.I understand Double is not the right way to store them but next best option is to use String as I use auto-generation of pojos and BigDecimal is not supported in that – Abhijeet Kushe Mar 08 '14 at 19:28

1 Answers1

0

The plugin which generates Pojos has accepted the feature request for adding an option to represent Double as BigDecimal

Abhijeet Kushe
  • 2,477
  • 3
  • 26
  • 39