How to round a double to 2 decimal places?

Java

If the value is 300.1234, it should be formatted to 300.12. If it is 300, then it should be 300.00
 

1
Answers

Replies

public static double round(double val, int places)


{


    if (places < 0) throw new IllegalArgumentException();



    long fact = (long) Math.pow(10, places);


    val = val * fact;


    long tmp = Math.round(val);


    return (double) tmp / fact;


}

 
 

If you want to unleash your potential in this competitive field, please visit the Java course page for more information, where you can find the Java tutorials and Java frequently asked interview questions and answers as well.

 

This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.