Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

help regarding rounding off numbers

Tags:

java

float per = (num / (float)totbrwdbksint) * 100;

i m getting the value of per as say 29.475342 . i want it to round off upto two decimal places only.like 29.48 .how to achieve this?

like image 998
Robin Agrahari Avatar asked Sep 15 '25 00:09

Robin Agrahari


2 Answers

You should do this as part of the formatting - the floating point number itself doesn't have any concept of "two decimal places".

For example, you can use a DecimalFormat with a pattern of "#0.00":

import java.text.*;

public class Test
{
    public static void main(String[] args)
    {
        float y = 12.34567f;
        NumberFormat formatter = new DecimalFormat("#0.00");
        System.out.println(formatter.format(y));
    }
}
like image 184
Jon Skeet Avatar answered Sep 17 '25 13:09

Jon Skeet


As Jon implies, format for display. The most succinct way to do this is probably using the String class.

float f = 70.9999999f;
String toTwoDecPlaces = String.format("%.2f", f);

This will result in the string "71.00"

like image 32
McDowell Avatar answered Sep 17 '25 13:09

McDowell