0

I'm writing a rules engine and one of the expressions the client is looking for is a "less than 1:80"

1:80 being a ratio

Is converting the ratio to a float a wise decision?

//psuedo-code
String givenRatio = "1:80";
String[] ratioNums = givenRatio.split(":");
float evalValue = Integer.valueOf(ratioNums[0]) / Integer.valueOf(ratioNums[1]);
John Giotta
  • 16,432
  • 7
  • 52
  • 82
  • Maybe, though I'd probably select double instead of float, BUT, it really depends on how you will use the data as to what precision you need. – Rabbit Guy May 03 '16 at 20:20
  • your String givenRatio is missing a double quotes at the end – ryekayo May 03 '16 at 20:24
  • What if the given ratio is like 2:84.5 ? then `Integer.valueOf ` will result in information loss, I would suggest `double eval = Double.valueOf( ratio[0])/Double.valueOf(ratio[2])` – SomeDude May 03 '16 at 20:25
  • 1
    `int` divided by `int` is an `int` (truncated), not a decimal number. In your case, `evalValue` would be assigned the value `0`. You need to cast to `float` *before* dividing. – Andreas May 03 '16 at 20:31
  • As for the question *"is it a wise decision"*, that is entirely depending on how it's used, and answers will be mostly opinion-based. – Andreas May 03 '16 at 20:34

2 Answers2

0

The division should be by float or double, with int you could lose information or even divide by zero. And about saving it, it depends. In this case ("1:int") I would have just saved it as a int constant and divide next expressions oppositely (ratioNums[1] by ratioNums[0]) and then compare. If it should change to expressions different from "1:int" such as "80:1", "2:5", I would keep it in float/double (as much precision as needed) and use the original comparison.

SarahGaidi
  • 51
  • 5
0

A float gives you approx. 6-7 decimal digits precision while a double gives you approx. 15-16. Also the range of numbers is larger for double.

A double needs 8 bytes of storage space while a float needs just 4 bytes.

Float and double datatype in java

Community
  • 1
  • 1