Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Math.round to round to one decimal place?

I have these two variables

double num = 540.512 double sum = 1978.8 

Then I did this expression

double total = Math.round((num/ sum * 100) * 10) / 10; 

but I end up with 27.0.

In fact I have many other variables and when I use them in the expression I always get a 0 in the tenth's place.

like image 822
user3344542 Avatar asked Mar 05 '14 01:03

user3344542


People also ask

What does it mean by rounded to 1 decimal place?

When you round to the first decimal place, or to the nearest tenth, the number in the hundredth point place will determine whether you round up or down. If the hundredths digit is a number between 5 and 9, round up to the nearest whole number.

Does Math round round up or down?

Here's the general rule for rounding: If the number you are rounding is followed by 5, 6, 7, 8, or 9, round the number up. Example: 38 rounded to the nearest ten is 40. If the number you are rounding is followed by 0, 1, 2, 3, or 4, round the number down.

What does round to 0.1 mean?

Correct to the nearest 0.1k means you are required to round the answer up or down to the nearest 10th (So 0.11246 would be 0.1, and 0.2704 would be 0.2).


2 Answers

Helpful method I created a while ago...

private static double round (double value, int precision) {     int scale = (int) Math.pow(10, precision);     return (double) Math.round(value * scale) / scale; } 
like image 62
jpdymond Avatar answered Oct 18 '22 19:10

jpdymond


try this

for example

DecimalFormat df = new DecimalFormat("#.##"); df.format(55.544545); 

output:

55.54 
like image 26
user3381763 Avatar answered Oct 18 '22 18:10

user3381763