-3
    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?

Mayur Patel
  • 319
  • 1
  • 2
  • 13
  • 2
    String.format("%.3f", answer) – Sachith Dickwella Nov 08 '19 at 06:35
  • *FYI:* That code doesn't compile. – Andreas Nov 08 '19 at 06:45
  • **1)** `4/16` is zero (`0`) since both operands are integer, integer division is performed - at least one of the numbers must be float, e.g. `(float)4/16` or `4F/16`; **2)** since the result is an `int`, it cannot be assigned to `Float` (would work if it was a primitive (`float`)) – user85421 Nov 08 '19 at 07:24

2 Answers2

1

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);
Defaulter
  • 358
  • 1
  • 4
  • 17
  • 1
    I recommend BigDecimal. – Vishwa Ratna Nov 08 '19 at 06:36
  • 1
    The question isn't to have decimal precision, it already has that, but to print the result with 3 fractional digits. – Andreas Nov 08 '19 at 06:41
  • @JoakimDanielson :My answer is generic and not specific to 3 decimal places. Formatting it with formatter converts it to string and thus makes overburden while operating numbers. BigDecimal on other hand can be customized for given decimal places – Defaulter Nov 08 '19 at 06:44
  • I agree with @Joakim Danielson. It would be more appropriate if this would be a comment instead of an answer. I decide to flag it. – Mayur Patel Nov 08 '19 at 06:50
  • 1
    @JoakimDanielson : I have updated my answer, can you recheck – Defaulter Nov 08 '19 at 06:53
  • 2
    `BigDecimal.ROUND_HALF_EVEN` is deprecated as of Java 9, and we are currently at Java 13. Since `RoundingMode.HALF_EVEN` has been around since Java 5, it's time to begin using it. – Andreas Nov 08 '19 at 06:55
-1

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

}
guninvalid
  • 411
  • 2
  • 5
  • 16
  • I wonder what happens with for example `0.249999`; (not to speak of an argument/variable called `float`) – user85421 Nov 08 '19 at 07:28
  • not very good to have a `split` and an `indexOf` for almost same reason , also I am pretty sure that `split(".")` does not do what you think it is - `.` means any character in regular expressions, you will end up with an empty array – user85421 Nov 08 '19 at 07:34