How to change decimal value string into int without loosing decimal values?

Viewed 28

I am working on a pretty old Java application and I can not change Integer field to something else which can hold decimal values, so I need to convert some decimal string like "100.00", "3.33" "33.44" to Integer without loosing fractional values.

@Test
public void NumberFormatTest(){
    String stringValue = "100.00";

    int testTest = ?  //what I can do here to get exact 100.00 in testTest variable ? 

    log.info("outPutValue {} ", testTest);
}

Currently its using Integer.parseInt(stringValue) and this is throwing

java.lang.NumberFormatException: For input string: "100.00"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
1 Answers

I am working on pretty old java code application and I can not change Integer field to something else which can hold decimal values

That is because int can only hold whole numbers. For decimal values you need to use float or double:

String s = "3.33";
double d = Double.parseDouble(s);

Alternatively, you might want to look into BigDecimal. Depending on your exact needs, this might be a better fit.

p.s. int, float and double are primitive types. Integer, Float and Double are class wrapper for those types. These are two different things. I recommend you read more about these differences to gain a better understanding.

Related