Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding a number up in Java [duplicate]

I dont get how rounding numbers up to certain decimal places I looked everywhere tried every thing

currently I have my program to round up to a whole number with double rACT = Math.ceil(ACT); double rSAT = Math.ceil(SAT); double rGPA = Math.ceil(GPA);

but i need it to round up to 2 decimal places

FYI - I am an High school student I really dont need something super complicated to do this cuz I need my methods to be less then 15 I can waste any lines

like image 903
Heon Jun Park Avatar asked Dec 12 '22 08:12

Heon Jun Park


2 Answers

There's probably a simpler way, but the obvious is:

double rSAT = Math.ceil(SAT * 100) / 100;

This turns a number like 2.123 into 212.3, rounds it to 213, then divides it back to 2.13.

like image 106
Brendan Long Avatar answered Dec 14 '22 20:12

Brendan Long


Usually, rounding is best done at the point of rendering the number (as a String, e.g.). That way the number can be stored/passed around with the highest precision and the information will only be truncated when displaying it to a user.

This code rounds to two decimal places at most and uses ceiling.

double unrounded = 3.21235;
NumberFormat fmt = NumberFormat.getNumberInstance();
fmt.setMaximumFractionDigits(2);
fmt.setRoundingMode(RoundingMode.CEILING);

String value = fmt.format(unrounded);
System.out.println(value);
like image 24
Mark Peters Avatar answered Dec 14 '22 22:12

Mark Peters