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.
Output
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.
Output
On a final note, you could just parse the value as a String and substring the value for 1 digit after the decimal point.
Output