# Help me to round off double, PLEASE JAVA MASTERS!!!

• May 5th, 2014, 02:45 AM
iamprogrammer
Help me to round off double, PLEASE JAVA MASTERS!!!
SOURCE CODE:

Double a, b, c;

a = Double.parseDouble(txt1.getText());
b = Double.parseDouble(txt2.getText());
c = a + b;
txt3.setText(""+c);
}

SAMPLE OUTPUT:

1.234 + 1.23 = 2.464

PROBLEM:

How to round off that sum 2.464 as 2.46?
Will I put ".2f"?
• May 5th, 2014, 03:04 AM
Cornix
Re: Help me to round off double, PLEASE JAVA MASTERS!!!
You could multiply by 100, turn it to an integer and cast it back to double dividing by 100.
• May 5th, 2014, 03:14 AM
iamprogrammer
Re: Help me to round off double, PLEASE JAVA MASTERS!!!
Good day sir!
Sir, I'm just a 17 year old Beginner Java Programmer, aiming to be become an expert someday.
Could you retype the code for me sir? Please Java Master!
• May 5th, 2014, 01:03 PM
amitection
Re: Help me to round off double, PLEASE JAVA MASTERS!!!
What Cornix said is absolutely correct. I am no expert in Java. I just started java 4 or 5 months ago & i really liked this language. I dont know what you are trying to do with your code but casting is something i know.
I would like to give you a simple example or casting & you could try this and adjust according to your code:

double temp = 2.464;
float res = (int)(temp*100); //this (int) does the casting and removes the last digit as you want
res = res/100;
System.out.println(res);

Hope this helped you a little bit!

--- Update ---

& with your code i think this should work

Double a, b, c;

a = Double.parseDouble(txt1.getText());
b = Double.parseDouble(txt2.getText());
c = a + b;
float temp = (int)(c*100);
temp = temp/100;
text3.setText(""+temp);
}
• May 5th, 2014, 01:37 PM
copeg
Re: Help me to round off double, PLEASE JAVA MASTERS!!!
Quote:

Sir, I'm just a 17 year old Beginner Java Programmer, aiming to be become an expert someday.
Could you retype the code for me sir? Please Java Master!
Perfect, but without continual practice writing code your attempts to become an expert get that much harder.

Quote:

How to round off that sum 2.464 as 2.46?
Do you wish to round, or floor? Because casting - as suggested above - will do the latter not the former.
• May 8th, 2014, 03:12 AM
varun7952
Re: Help me to round off double, PLEASE JAVA MASTERS!!!
Use Printf Statement for formatting text