K
K
Klin Klinom2014-09-28 21:21:29
Java
Klin Klinom, 2014-09-28 21:21:29

How to round a number to two decimal places (Java)?

Hello!
How to round a number to two decimal places using a specific example:
4182c9cd7c243c503475109167066c25705197f1
Thank you!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Martivic, 2014-09-28
@yramarad31

private double round(double number, int scale) {
int pow = 10;
for (int i = 1; i < scale; i++)
pow *= 10;
double tmp = number * pow;
return (double) (int) ((tmp - (int) tmp) >= 0.5 ? tmp + 1 : tmp) / pow;
}

O
Odissey Nemo, 2014-10-28
@odissey_nemo

For a specific example, the top solutions may be suitable, but in the general case, I'm not very sure.
It's guaranteed to be like this:

jLabel5.setText(jLabel5.getText() + String.format( Locale.US, "%.2f", y) );
Here the separator is clear - a point, and the form of presentation will not suddenly turn out to be scientific.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question