Kaygee
Kaygee

Reputation: 143

how to validate float against specific format in java?

I want to validate the float type data. I get the rules defined as

int precision1 = 3;
int precision2 = 2;

The above rule indicates the data format should be of 999.99

The expected validation of 1234.56, should fail from the above rule. Also expected validation should fail for float 123.456 from the above rule. Expected validation of 123.33 should be successful.

Any thoughts would be appreciated on validation process.

Thanks, Kaygee

Upvotes: 0

Views: 2860

Answers (2)

extraneon
extraneon

Reputation: 23960

The user inputs a String, it is converted somewhere to float, and you try to validate the float. You can't do it like that.

The String representation of a float is a human artifact. Plus, a float tends to only approximate (very closely) the value of a converted String.

If you want to validate the precision the only way to go is to validate the user input String. And store it like a String if you want to keep the precision.

If you need a number, for instance to compute with, use a BigDecimal. It is designed to keep the precision exactly as given (important for financial calculations). They are not very nice to work with, but that's the price you pay if you want exact non-integer values.

EDIT

How to use a BigDecimal.

 BigDecimal b1 = new BigDecimal("1234.23");
 System.out.println(b1 + " scale was " + b1.scale()); 2
 BigDecimal b2 = new BigDecimal("1234.523536223");
 System.out.println(b2 + " scale was " + b2.scale()); // 9

You can obviously test the "precision" by using the scale. If b1.scale() == 2 || b1.scale() == 3 => valid.

Upvotes: 1

Greg
Greg

Reputation: 1146

Quick and dirty:

    int precision1 = 3;
    int precision2 = 2;
    float var = 123.12f;
    String varStr = String.valueOf(var);
    if (varStr.length() == (precision1 + precision2 + 1) && varStr.indexOf(".") == precision1) {
        System.out.println(true);
    } else {
        System.out.println(false);
    }

Upvotes: 2

Related Questions