I am trying to convert a float to BigDecimal then do some maths. After that i would require the final results in Float.
From what I known, the only safe way to get a float to become a BigDecimal number is to use the string constructor.
I have two approaches but both didnt work. Both gives me an additional 0.000001 value
Approach #1:
Float num1 = 13.846154f;
BigDecimal calculation = new BigDecimal(Float.toString(num1));
BigDecimal num2 = new BigDecimal("2.0").add(calculation);
Float finalResults = num2.floatValue();
Approach #2:
Float num1 = 13.846154f;
BigDecimal calculation = new BigDecimal(Float.toString(num1));
BigDecimal num2 = new BigDecimal("2.0").add(calculation);
Float finalResults = Float.parseFloat(num2.toString());
Is there a way to safely do the math and not lose precision when i convert the number back to float?
Edit #1 I did some testing and found something weird.
Float original = 13.846154f;
BigDecimal originalNum = new BigDecimal(Float.valueOf(original));
BigDecimal numTwo = new BigDecimal("14.0");
BigDecimal numThree = new BigDecimal("20.0");
BigDecimal numFour = new BigDecimal("30.0");
numTwo = numTwo.add(originalNum);
numThree = numThree.add(originalNum);
numFour = numFour.add(originalNum);
It is still adding that extra 0.000001..