Float x = 4;
Float answer = 4/16;
The answer for this is 0.25
, but I want to display the answer upto 3 decimal places, like 0.250
.
How to achieve that? Please help?
Float x = 4;
Float answer = 4/16;
The answer for this is 0.25
, but I want to display the answer upto 3 decimal places, like 0.250
.
How to achieve that? Please help?
To have decimal precision, use BigDecimal
class.
Number of decimal places can be specified in setScale as below
BigDecimal a = new BigDecimal("0.25");
a = a.setScale(3, BigDecimal.ROUND_HALF_EVEN);
One possible solution is to use toString()
cut off at the decimal point using split(".")
. If the length of the resulting string is less than 3, add zeroes until the length is three. If it is greater than three, cut off there. Such as:
public String triplePrecision(Float float) {
String tmp = float.toString();
int length = tmp.split(".")[1].length();//numbers after decimal
for (int i = 0; i < 3 - length; i++) {
tmp += "0"; //appending zeroes
}
return tmp.substring(0, indexOf(".") + 3); //start to 3 places after decimal
}