Rounding Doubles
As posted in another thread, I am writing code for an object oriented programming class. My program will multiply doubles, but I want exactly two decimal places in the answers. Any suggestions?
public class DecimalNumber {
private int intPart;
private int decimalPart;
private int accuracy;
public DecimalNumber(int ip, int dp, int acc) {
intPart = ip;
decimalPart = dp;
accuracy = acc;
public String toString() {
return Integer.valueOf(intPart).toString() + new DecimalFormatSymbols().getDecimalSeparator() + Integer.valueOf(decimalPart).toString().subString(0,accuracy);
}I left the trivial exercise of implementing mathematical operations using these numbers to you.
Similar Messages
-
Rounding Doubles to Two Decimal Places
Hi All,
I've searched the archive and found a few different posts regarding restricting the number of decimal places in doubles. However they all suggest different methods, BigDecimal, NumberFormat etc.
Which is the simplest method of rounding a number say 10.023445656 to 10.02?
I tried using the java.text.NumberFormat but this turns the double into a string and I need the end result to be a double.
ThanksHi All,
I've searched the archive and found a few different
posts regarding restricting the number of decimal
places in doubles. However they all suggest different
methods, BigDecimal, NumberFormat etc.
Which is the simplest method of rounding a number say
10.023445656 to 10.02?
I tried using the java.text.NumberFormat but this
turns the double into a string and I need the end
result to be a double.
ThanksI ahve a small code that can do the work for u:
import java.text.*;
double format(double val, int dec){
double multiple=Math.pow(10,dec);
val=Math.round(val*multiple)/multiple;
DecimalFormat df=new DecimalFormat("0.00");
String format=df.format(val);
double dval=Double.parseDouble(format);
return dval;
}//end of functionHope that helps! -
Rounding Doubles in java1.2
How do I round a double value in java 1.2? I can't seem to figure it out. Thanks.
Wow, I feel silly - why have I never seen this B4???int i = (int)(g + 0.5);Well ... I still feel silly, so much for the cleansing power of confession.
This thread has got untidy and I thought I'd do some repair, sorry - Michael is it (??? the origial poster)
I take full responsibility. Let me tidy up;-import java.text.*;
class wholeNumber {
public static void main (String []args) {
System.out.println("Results of decimal formatting and rounding.\n");
double d = 1.39328;
int i = (int)(d + 0.5);
System.out.println("Casting to int it is;- " + i);
System.out.println("Using Math.round it is;- " + (Math.round(d)));
DecimalFormat twoPlaces = new DecimalFormat("0.00");
System.out.println("Result to 2 decimal places is;- " + twoPlaces.format(d)); -
Rounding double for string purposes
Hello Forum,
I have small problem:
Let say I need to convert meters to feet. I have jTextFieldMeter for inputing the meters and jButtonCalculateFeet to calculate to feet. I also have jTextArea where resultS ARE displayed.
Now, calculation is perfect (button action):
double feet = Double.parseDouble(jTextFieldMeter) * 3.28083;
Here is the problem: How do I display each result in jTextArea in new line and in this order;
(jTextFieldMeter.getText() + " meters is " + feet(???) + " feet.") - but feet should be rounded after first decimal number so I get in jTextArea :
"1 meters is 3.3 feet"
And another question, how do I write in next line in jTextArea, so there are more lines (multiline).
Now I get just one same line for each new result (deletes (or overvrites?) old result)
Since I am a beginner I believe I might complicated simple task. If I am not understandable I will gladly explain more!
Thanks and sorry for my English
Kind regards, BeezgetzHello Prigas,
Thanxs for your reply. It helped me graet deal!
JTextArea.append("Your text with new line\n"); works a charm!
As for decimal places...
I got it just fine, but that link of yours gave me another thing to worry.
Is there a universal decimal separator? I mean . (point) or , (comma)?
If I save my doubles into xml in my room in Slovenia and send those saved doubles to some dude in Finland, how does his computer interprets decimal separator?
Am I makimg sense?
Kind regards, Beezgetz -
Rounding Double in J2ME, need help
hi....
i using J2me to develop scientific calc.
but i have problem with rounding the double result.
when using J2SE i can use DecimalFormater...
is there something like that in J2ME ???
tanks...1. Convert the double to a string using Double.toString(yourDouble)
2. Use yourString.substring and indexOf(yourString, ".") to get the part you need. Concatenate trailing zeros if needed.
3. Convert the resulting string to a double using Double.parseDouble(YourResultString)
The string manipulation will be different depending on whether you want to round to a certain number of decimals or a certain number of significant figures.
If you need a code segment pls supply more details, have tested this approach and it works.
Regards, Darryl -
Help - Rounding Double Value to 1d.p
Hi there, I have a value which is going to be entered via keyboard it will be something like $309.99 or $856.87 and I need it to be rounded to the nearest 10C. E.g $309.99 would become $310.00 and $856.87 -> $856.90
It doesn't even need to be at 1d.p but just round up to nearest 10C...
Any help will be greatly appreciated..
Thanks..I need it to be rounded to the nearest 10C.It's not quite clear what you mean by this. Should the number itself change to
the nearest 0.1 of a dollar? Or should string used to display the number
be made to resemble the examples you give ($310.00 etc)? The two
things are very different, although both could be described as "rounding".
public class RoundEg {
public static void main(String[] args) {
double d = 12.345;
// creates the string "$12.30"
String s = String.format("$%.1f0", d);
System.out.println(d + " --> " + s);
// changes d to 12.3
d = Math.round(d * 10) / 10.0;
System.out.println(d);
}String.format() is 1.5, you might also have a look at the DecimalFormat class. -
hi,
I have the following code :
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
String fTax1 = nf.format( 1.245 );
String fTax2 = nf.format( 1.255 );
String fTax3 = nf.format( 1.265 );
the results are :
fTax1 = 1.24
fTax2 = 1.26
fTax3 = 1.26
Can anyone help me to answer that ???
Thanks !!!!Banker's rounding is being used here
It rounds the numbers to the nearest even digit - 1.245 rounds to 1.24, 1.255 rounds to 1.26, 1.265 rounds to 1.26.
From the javadocs of DecimalFormat and BigDecimal.ROUND_HALF_EVEN:
Rounding
DecimalFormat uses half-even rounding (see ROUND_HALF_EVEN) for formatting.
ROUND_HALF_EVEN
public static final int ROUND_HALF_EVEN
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations. -
Rounding up doubles to 2 decimal places
I'm currently rounding up a double in my program using Math.round(double)
However I want to strip any trailing zeros from the output, so:
1.235 would round to 1.24
but 1.00 would round to 1
How would I go about doing this?Also I'm making my own function to round the doubles,
and they are returning doubles so I cannot return a
string.If they are returning doubles that the number of "trailing zeros" is irrelevant, as that is formating. Really you should keep the precision until you want to display it, then use the formatter above.
What are you doing?
I'm going to take a shot in the dark; has this got something to do with money? -
Rounding and displaying doubles
How do you stop a double (eg 12646903) being displayed as 1.2646903E7? ??? .
LyndaIf you are talking about rounding doubles, you should take a look at the BigDecimal class. For example if you where rounding currency and lets say you are trying to convert 1.0 at a rate of .787564 you would normally get
1.26973807842918162841369082385685 but if you wanted to round this to 1.27 you could do the following ...
double myAmount = 1.0;
double myRateOfExchange = .787564;
double myDouble = myAmount / myRateOfExchange;
BigDecimal bd = new BigDecimal(myDouble).setScale(2,BigDecimal.ROUND_HALF_DOWN);You will need to import BigDecimal to use it. import java.math.BigDecimal;Depending on how you want to round you may want to look at the field index for the BigDecimal class.
Hope this helps -
Rounding xs:double value
Hi in bea xquery function pallette we only foung round() for decimal type.But we had a requirement to round xs:double values.
How can i achive this ,any method for round double values or to convert double to decimal.does round( $someDouble ) not work?
Can you please try a few things yourself before posting?
If you already have, can you please post what you have tried? -
Formatting a Double to a String for Swing output
Hi, I'm new to Java and I'm working on a project with AWT & Swing. I'm trying to read in a user entered number, convert it to a double, work on it and then output the String value of the result with only two decimal places. The code I have is:
public void actionPerformed(ActionEvent e)
double result = 99;
double temp;
DecimalFormat newTemp = new DecimalFormat("#,###.00");
if (e.getSource() == bConvert1)
temp = (Double.parseDouble(tTemp1.getText().trim()));
result = (temp*1.8)+32;
newTemp.format(result);
tResult1.setText(String.valueOf(result));
else if (e.getSource() == bConvert2)
temp = (Double.parseDouble(tTemp2.getText().trim()));
result = (5.0/9)*(temp-32);
newTemp.format(result);
tResult2.setText(String.valueOf(result));
This is working for some values, but for some values entered, the result displayed is just the remainder.The reason it doesn't always work could be because DecimalFormat (for reasons known only to Sun) uses ROUND_HALF_EVEN...
This means that you will have to round the value to the number of decimal places you require before calling format()
I use something like the following formatter class
class Formatter {
public static final int DEFAULT_PRECISION = 2;
public static final String DEFAULT_PATTERN = "#.00";
public static final String ZEROS = "0000000000000000";
public static String convertDoubleToString(Double d) {
return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
public static String convertDoubleToString(double d) {
return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
public static String convertDoubleToString(Double d, int precision) {
return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
public static String convertDoubleToString(double d, int precision) {
return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
public static String convertDoubleToString(Double d, String pattern) {
return new DecimalFormat(pattern).format(d.doubleValue());
public static String convertDoubleToString(double d, String pattern) {
return new DecimalFormat(pattern).format(d);
private static final double round(Double d, int precision) {
double factor = Math.pow(10, precision);
return Math.round((d.doubleValue() * factor)) / factor;
private static final double round(double d, int precision) {
double factor = Math.pow(10, precision);
return Math.round((d * factor)) / factor;
} -
Going nuts over modulo of two doubles
consider:
double x=2.0;
double y=0.1;
double z=x%y;
boolean perfectFit = (Math.round(x/y)==x/y);
System.out.println("x="+x+",y="+y+",z="+z+",perfectFit="+perfectFit);
// surprisingly (at least for me),
// while perfectFit is true (as expected), z is not zero at all:
x=2.0,y=0.1,z=0.0999999999999999,perfectFit=true
am I missing something?What happens is quite normal and you will understand this if you try:
public class Modulo {
public static void main (String [] args) {
double x = 2.0;
double y = 0.00001;
double z=x%y;
boolean perfectFit = (Math.round(x/y)==x/y);
System.out.println("rounded: "+Math.round(x/y));
System.out.println("not rounded: "+x/y);
System.out.println("modulo: "+z);
System.out.println(perfectFit);
}You see Math.round(double) returns a long and you play with double. That means that you lose a bit of presision here... In the above example this becomes obvious for a big number.
Hope that helped
afotoglidis -
Rounding minutes to nearest five.
Hi,
I have tried the various methods suggested on other forum messages but to no avail.
I have a GUI that acts as the client for a reminder system i am making for some coursework.
It contains a combo box with values for the user to select a time from, however the time is not displayed in the format i would like it to be.
I would like the current time from the instance of calendar i have created to be rounded to the nearest five up.
The code i have for the combo box at the moment is:
cal.set(cal.MINUTE, (int)Math.round((double)cal.MINUTE));
n=0;
int z = 0;
while(z<288)
cal.add( cal.MINUTE, n);
s = DateFormat.getTimeInstance(DateFormat.SHORT).format(cal.getTime());
time_cb.addItem(s);
n=5;
z++;
This code always sets the first value of the combo box to 10 minutes past the hour and increments it by five from there. This happened with all the other methods i tried from the other forums also.
I would like it to round to the nearest five the current time and increment by five from this time.
Thanks for your time and help.Hi,
I have tried the various methods suggested on other
forum messages but to no avail.
I have a GUI that acts as the client for a reminder
system i am making for some coursework.
It contains a combo box with values for the user to
select a time from, however the time is not displayed
in the format i would like it to be.
I would like the current time from the instance of
calendar i have created to be rounded to the nearest
five up.
The code i have for the combo box at the moment is:
Your first line is wrong. Your setting the calendar minutes field to
some random value, cal.MINUTE, which has nothing to do with the current minute. You need to do
Calendar c = new GregorianCalendar()
which automatically sets the current minute
cal.set(cal.MINUTE,
(int)Math.round((double)cal.MINUTE));
n=0;
int z = 0;
while(z<288)
cal.add( cal.MINUTE, n);
s =
=
DateFormat.getTimeInstance(DateFormat.SHORT).format(ca
.getTime());
time_cb.addItem(s);
n=5;
z++;
This code always sets the first value of the combo box
to 10 minutes past the hour and increments it by five
from there. This happened with all the other methods i
tried from the other forums also.
I would like it to round to the nearest five the
current time and increment by five from this time.
Thanks for your time and help. -
If I have a double value, how can I check that the double meets a specified resolution.
ie. if I have a specified resolution of 0.02, how can I verify that a double value is evenly divisible by that resolution.
I am dealing with a JTextField so I can verify that the text value does not contain more decimal places than would be allowed by the resolution.
Thanks.I was thinking if the resolution was passed in as a string "0.02" I could determine that the number of allowed decimals is 2. Then if the text field is "12.24" I could do the following.
if ( Math.round(Double.parseDouble (getText()) * Math.pow (10, numDecimals)) % Math.round (resolution * Math.pow (10, numDecimals)) == 0)
// text is validis there a better way then passing in the resolution as a String? I suppose I could pass in the resolution a a double and pass in an int the represents the number of decimals.
Any thoughts? -
Setting double value precision
Is there any way to set the precision on a double.
Example:
double = 25.00016000207654
precision = 4 decimal places (or some value 'x')
So I am looking for 25.0002 (this value will then be converted to a string and then displayed).Here is a simple little program that will allow you to round and format the way you wanted:
import java.text.*;
public class testFormat {
public static void main(String[] args) {
double x=25.00016000207654;
x=Round(x,4);
DecimalFormat NF=new DecimalFormat("0.####");
String formatted=NF.format(x);
System.out.println(formatted);
public static double Round(double x, int dec) {
double multiple=Math.pow(10,dec);
return Math.round(x*multiple)/multiple;
}V.V.
Maybe you are looking for
-
"The operation could not be completed" Creating an iMovie
Hello, Every time I go to create a Movie or project in iMovie it says, "The operation could not be completed" followed by "No other information is available about the problem." I have been recording several videos, and I need to edit them, get them o
-
Can primary key be changed?
Hi all, I found that if primary key is changed, the SQL statement generated is strange. For example, I have an object A, with primary key = 12345. In the UoW, I update the primary key to 1000. The SQL statement generated would be something like "UPDA
-
ANM 5.2 unable to import ACE 4710
Good day, I am currently experiencing a problem while trying to import multiple 4710 ACE Appliances into ANM. ANM version is 5.2 and ACE 4710 Appliances version is 5.1.2. The error message is the same for all Appliances (currently 14, more to be depl
-
Error When Installing X11...
I was trying to install X11 so I can use GIMP, a free photoshop like program. Anyways, when trying to instal, it says "You Cannnot install X11 on this volume. Software already exists on your computer. I was trying to install it on the Macintosh HD. I
-
Carry Forward of Budget in Investment Program
Dear Experts I am trying to carry forward the budget of the Investment program from FY 2010 to FY 2011. I have used IM27 for copying the program structure and Internal Orders. The Budget Values, Commitments of IO has been carried forward but I am not