Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

Round according to nearest decimal value - java

I have used this one

Math.round(input * 100.0) / 100.0;

but it didn't work with my requirement. I want to round into two decimal points according to nearest decimal value.

firstly I want to check fourth decimal value if it is 5 or above I want to add 1 into 3rd decimal value then want to check 3rd one if it is 5 or above I want to add 1 into 2nd one

ex: if I have 22.3246

refer above example number. 4th decimal no is 6. we can add 1 into 3rd decimal value.

result : 22.325

now 3rd decimal no is 5. we can add 1 into 2nd decimal value

result : 22.33

I want to get result 22.33


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to respect the 4th decimal digit, you can do it in this way:

double val = Math.round(22.3246 * 1000.0) / 1000.0;
double result = Math.round(val * 100.0) / 100.0;
System.out.println(result); // print: 22.33

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...