I have a method which sometimes returns 0.28 / 0.23 . I am using the below class
DecimalFormat df2 = new DecimalFormat("#.#");
but here I need this code to return me 0.2 every-time , but when its more than 0.25 its returns 0.3 by rounding it off to closet decimal .
But i want my code to return 0.2 every-time the value varies from 0.21 to 0.29. can someone help me with this ?
There are a few ways to accomplish this.
Casting a floating-point value to an integer will truncate the decimal.
So, you could utilize this by first multiplying by 10, truncating the value, and then re-dividing by 10.
float valueA = 0.28f;
float valueB = 0.23f;
valueA = ((int) (valueA * 10)) / 10f;
valueB = ((int) (valueB * 10)) / 10f;
Output
valueA = 0.2
valueB = 0.2
Additionally, you can utilize the BigDecimal class.
The setScale method allows you to set the amount of digits after the decimal point, in addition to setting a RoundingMode.
There are numerous types of rounding modes, see the RoundingMode JavaDoc linked above, for a table of values.
I believe you are looking for FLOOR, or DOWN, for the truncation.
Here is an example using DOWN.
BigDecimal valueA = new BigDecimal("0.28");
BigDecimal valueB = new BigDecimal("0.23");
valueA = valueA.setScale(1, RoundingMode.DOWN);
valueB = valueB.setScale(1, RoundingMode.DOWN);
Output
valueA = 0.2
valueB = 0.2
On a final note, you could just parse the value as a String and substring the value for 1 digit after the decimal point.
float valueA = 0.28f;
float valueB = 0.23f;
String stringA = String.valueOf(valueA);
valueA = Float.parseFloat(stringA.substring(0, stringA.indexOf('.') + 2));
String stringB = String.valueOf(valueB);
valueB = Float.parseFloat(stringB.substring(0, stringB.indexOf('.') + 2));
Output
valueA = 0.2
valueB = 0.2