If I have an output of any double or integer that needs to be rounded to a certain number of decimal places, how would I code that? As always there are many ways to do this but, again, as always, I'll be looking for the simplest way to do such a thing without compensating any viability in my program. Thanks for all the help.

## All 7 Replies

There is Math.round() that rounds a double:
10.9 --> 11.0
10.4 --> 10.0

If you want a certain number of decimal digits you can:

Multiply (for example) the number with 100, then round it with the above method and then divided again with 100:
10.123456 --> 1012.3456 --> 1012.00 --> 10.12

Or :

java.text package
that has this:
DecimalFormat

So exactly how would I write this? Would I type in the variable I would like rounded and then Math.round(), or visa versa?

take a look at the Math api's

Well all I need to do is make a double like 23.5 to be 23.50 and longer ones like 23.556 to be 23.55 or 23.56. Would I do this as doublevalue = Math.round(2);? I seriously just started programming with java so sending me to those elongated complicated reference sheets won't do too much help as I've only learned basic coding and algorithmic functions in Java.

That reference sheet has all the methods you will need as well as what they do and how they are called.

There is Math.round() that rounds a double:
10.9 --> 11.0
10.4 --> 10.0

If you want a certain number of decimal digits you can:

Multiply (for example) the number with 100, then round it with the above method and then divided again with 100:
10.123456 --> 1012.3456 --> 1012.00 --> 10.12

``````double d = Math.round(10.9);
System.out.println(d); //will print 11.0

double d = Math.round(10.4);
System.out.println(d); //will print 10.0``````

Well all I need to do is make a double like 23.5 to be 23.50 and longer ones like 23.556 to be 23.55 or 23.56. Would I do this as doublevalue = Math.round(2);? I seriously just started programming with java so sending me to those elongated complicated reference sheets won't do too much help as I've only learned basic coding and algorithmic functions in Java.

Your nick is IMtheBESTatJAVA and you are telling us you are just beginner? Good sarcasm. References are complicated sometimes, but most of the cases it appears to be complicated because of lack of patience.
Math.round() takes the number you want to roundup. That won't give you any decimal. After you round the number, if you divide it by 100.0, that shifts the number to two decimal points.
I am referring you to this for more explanation: http://www.daniweb.com/forums/thread32513.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.