NumberFormat Rounding
I am trying to get the age of a person. I get the age plus
all of the numbers after the decimal
When I numberformat it is rounding the number up. so if they
are actually 7 it rounds it to 8. No good in my world.
I simply want the number in front of the decimal and igore
thre rest.
<cfset foo=#numberformat(age,"9")#>
Suggestions?
Thank you!
Similar Messages
-
Any plan to fix issue JDK-8039915 re NumberFormat rounding?
It's been several months since issue https://bugs.openjdk.java.net/browse/JDK-8039915 was reported in Java 8. This bug causes some very unexpected results from NumberFormat's HALF_UP rounding logic specifically, there are many cases where for two numbers x and y, x is > y, but round(x) < round(y). This issue is our only remaining blocker to migrate to Java 8.
Can anyone in Oracle provide an update?If u haven't resolved this issue yet, I just did.
What I did:
1. Toggle the hold switch (turn it on and off)
2. Reset to 'Disk Mode'
by pressing the 'Play' and center buttons
simultaneously
(it may take a couple of trials to get it right)
3. Update iPod with latest iTunes in Disk mode.
4. Incase the 'Can't find firmware' error msg is displayed,
follow the instructions in the link given below:
http://docs.info.apple.com/article.html?artnum=304309
Toshiba SatelliteA30-203, Compaq Presario 3000 Windows XP Pro -
Cant find method? and i cant figure out how to round a decimal....
when i compile this it says "getAverage not found in class AverageGradeUser" - look at actionPeformed() to find where its used at....how do i fix this, i had it working but somehow messed it up and when the new average is figured and put in the results textfield, how can u round it off to the nearest tenth (0.1)..ive tried using NumberFormat and related things but couldnt get it to work
please help me
thanks
p.s. keep in mind i am a rookie-rookie-rookie in java programming
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AverageGradeUser extends Applet implements ActionListener
/****InstanceVariables****/
public TextField input;
/*****InitMethod****/
public void init()
Label directions = new Label("Enter a grade percent: ");
input = new TextField(10);
Label results = new Label("Your new average is: ");
TextField output = new TextField(10);
add(directions);
add(input);
add(results);
add(output);
output.setEditable(false);
input.addActionListener(this);
} // init()
public void actionPerformed(ActionEvent e)
double grade = Double.parseDouble(input.getText());
if (e.getSource() == input)
getAverage(grade);
} // actionPerformed()
} // AverageGradeUser class
============================================================
(the classes are in separate files but both are in the project)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AverageGrade
/****InstanceVariables****/
private double total = 0;
private double counter = 0;
private double average = 0;
private TextField input;
private TextField output;
/****ConstructorMethod****/
public AverageGrade()
/****AccessMethod****/
public void getAverage(double g)
total += g;
counter ++;
average = total / counter;
output.setText(average + " " + getLetterGrade(average));
input.setText("");
} // getAverage()
private String getLetterGrade(double avg)
if (avg >= 90)
return "A";
else if (avg >= 80)
return "B";
else if (avg >= 70)
return "C";
else if (avg >= 60)
return "D";
else if (avg < 60)
return "F";
else
return "error";
} // getLetterGrade()
} // AverageGrade classAccording to the code you have posted, method "getAverage()" is defined in class "AverageGrade" -- and not in class "AverageGradeUser". Therefore, you have two choices (in my opinion):
1. Add the definition of method "getAverage()" to class "AverageGradeUser"
2. Change the "actionPerformed()" method:
Replace the line:
getAverage(grade)with
new AverageGrade().getAverage(grade)Hope this helps you.
Good Luck,
Avi. -
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 off to two decimal places
Hello,
For simplicity, is there a method which will round off
a double variable to two decimal places.
Excample: if I have a result which equals 2.1999998
and I want to display this as 2.20 in a TexTField.
Any help would be much appreciated.
ThanksIf you are trying to do dollars and cents, I further recommend you use:NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
String currencyOut = currencyFormatter.format(yourNumber);to format your numbers as they will give the correct precision for international currencies simply by setting the locale, and they will also automatically handle the currency symbols ($, DM FR, etc.)
Doug -
Rounding a number to 2 decimal places
Is there anyway using the Round function to get it to .2
decimal places rather than the nearest whole figure...
I have a table that contains product prices, some of these
are already in a nice 2 decimal format (such as 7.99 or 12.49) but
I also have some that are like this-43.990002 and this-8.9899998.
What is the best way to round these to 2 decimal places?
thanksDo some experimentation. If you are using numberformat you
might not need to use round. -
Rounding off to 2 decimal places
Hi,
I use "Double" for my calculations and since I am working with $$ ;-) I need to round it off at 2 decimal places. Any quick way to do this? or do I have to write some major code for that?
ThanksThis works for all the test cases. Try this
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
class RoundOff {
public static void main(String args[]) {
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("173449.8"));
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("173449.98"));
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("-1.0"));
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("-1.0"));
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("-141.036"));
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("-00.1"));
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("-0.0"));
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("173449.98"));
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("173449.0.54"));
//RARE EXCEPTIONS BUT WONT OCCUR
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("0125."));
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("0125.979.79E"));
//RARE EXCEPTIONS BUT WONT OCCUR
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("173449.2354"));
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("173449.9874"));
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("173449.999"));
System.err.println(" FINAL OUT PUT >>> " + formatPrecision("173449.999"));
private static String formatPrecision(String s) {
if (s == null || s.trim().length() == 0) {
return "0.00";
try {
if (Double.parseDouble(s) == 0) {
return "0.00";
catch (java.lang.NumberFormatException nfe) {
return s;
double d = 0.00;
int ind = s.indexOf('.');
String dec = "";
if (ind > 0) {
dec = s.substring(ind);
if (dec.length() == 1) {
s = s.concat("00");
return s;
if (dec.length() == 2) {
s = s.concat("0");
return s;
if (dec.length() == 3) {
return s;
if (ind == -1) {
return s.concat(".00");
try {
d = Double.parseDouble(s);
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); //2 decimal places
d = bd.doubleValue();
NumberFormat formatter = new DecimalFormat("0.00");
return String.valueOf(formatter.format(d));
catch (java.lang.NumberFormatException nfe) {
return s;
} -
When using Math.round, I know to round to 2 decimal places it would be Math.round(variable * 100.0)/100.0. I have this in one program and it works. (answer = Math.round(answer*100.0)/100.0;) I have it in another program and it doesn't (double answer = Math.round(balances [looper]*100.0)/100.0;// balances is declared as double balances [] = new double [numberOfCustomers];) What am I doing differently that I should be looking for.
Hi,
Please try using java.text.DecimalFormat class. This class is a subclass of java.text.NumberFormat. You can read about this class from JDK documetation.
HTH
VJ -
How can i HALF_ROUND_UP using DecimalFormat and NumberFormat
hi
currently what i did is
public static String formatNumber(double value){
NumberFormat formatter = new DecimalFormat("#.00");
return formatter.format(value);
}1. 12.344 ==> 12.34
2. 12.346 ==> 12.35
3. 12.345 ==> 12.34
But what i want for case number 3 is 12.345 ==> 12.35
Because in oracle 12.345 it will always round up
How do i do that using DecimalFormat and NumberFormat??
ThanksAs long as you're using Java 6, you can specify the rounding using
setRoundingMode(RoundingMode roundingMode)
Sets the RoundingMode used in this DecimalFormat.For the available modes - including "round half up" - see the Java 6 RoundingMode enum API. -
Using currency format to round results (error cannot find symbol)
Hi i have a small program that converts currency and want to round the numbers up to 2 d.p i have chosen to use the command
numberFormat(txtOutput, "0.00");
But i cannot figure out where to put it in my program as it just returns errors like cannot find symbol. Could anyone please help?
this is the program that it is going to go into
double x;
double y;
double z;
x = Integer.parseInt(txtInput.getText());
y = 0.748279;
z = Double.parseDouble(txtExchange.getText());
if (z > 0)
txtOutput.setText('?' + Double.toString( x * z ));
else
txtOutput.setText('?' + Double.toString( x * y ));I now have this but it is still returning the error illegal start of expression for the line "import java.text.DecimalFormat;". And i have checked the braces and they appear correct
import java.text.DecimalFormat;
numberFormat(txtOutput, "0.00");
DecimalFormat df = new DecimalFormat("0.00");
double x = Integer.parseInt(txtInput.getText());
double y = 0.748279;
double z = Double.parseDouble(txtExchange.getText());
if (z > 0){
txtOutput.setText('?' + df.format( x * z ));
} else {
txtOutput.setText('?' + df.format( x * y ));
} -
Having trouble with rounding and if/else
I am trying to write a program that reads 2 floating-point numbers and test if they're the same when rounded to 2 decimal places and whether they diff by less than 0.01. I'm having trouble compiling it, with errors such as
"C:\Documents and Settings\John\My Documents\Test2.java:24: 'else' without 'if' else"
C:\Documents and Settings\John\My Documents\Test2.java:18: cannot find symbol
symbol : method round(double,int)
location: class java.lang.Math
double round1 = Math.round(firstinput,2);
^
C:\Documents and Settings\John\My Documents\Test2.java:19: cannot find symbol
symbol : method round(double,int)
location: class java.lang.Math
double round2 = Math.round(secondinput,2);Here is the code:
import java.util.Scanner;
import java.text.NumberFormat;
import java.math.*;
import java.lang.Math;
public class Test2
public static void main( String args[] )
Scanner sc = new Scanner( System.in);
System.out.println("Enter your first floating-point number: ");
double firstinput = sc.nextDouble();
System.out.println("Enter your second floating-point number: ");
double secondinput = sc.nextDouble();
double round1 = Math.round(firstinput,2);
double round2 = Math.round(secondinput,2);
double total = round1 - round2;
if(round1 == round2);
System.out.print("They are the same when rounded to two decimal places. \n");
else
System.out.print("They are not the same when rounded to two decimal places. \n");
if(total<1.01 && total>0.99)
System.out.print("They differ by less than 0.01. \n");
else
System.out.print("They do not differ by less than 0.01. \n");
}Are you restricted to Math.round()? Try reading about DecimalFormat:
http://java.sun.com/j2se/1.4.2/docs/api/java/text/DecimalFormat.html
Your code with DecimalFormat:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.##");
Scanner sc = new Scanner( System.in);
System.out.println("Enter your first floating-point number: ");
double firstinput = sc.nextDouble();
System.out.println("Enter your second floating-point number: ");
double secondinput = sc.nextDouble();
double round1 = Double.parseDouble(df.format(firstinput));
double round2 = Double.parseDouble(df.format(secondinput));
double total = round1 - round2;
if(round1 == round2)
System.out.print("They are the same when rounded to two decimal places. \n");
else {
System.out.print("They are not the same when rounded to two decimal places. \n");
if(total<1.01 && total>0.99) //<== Rather redundant, why not just use total == 1
System.out.print("They differ by less than 0.01. \n"); //<== From the above if statement, it seems if you are looking to see if the 2 numbers differ by less than 1.00, and not 0.01. The same goes for the else statement below
else
System.out.print("They do not differ by less than 0.01. \n");
}Also, when I ran your program with the latter code and entered two same floating point numbers, it also printed out "They do not differ by less than 0.01." I've added curly brackets around the outer else statement to ensure that it does not happen. It's best to use curly brackets in structured statements if their function exceeds more than one line; for stability and legibility.
Also, read my comments. -
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. -
I have a user who is complaining that the numbers on her report don't add up to the total that's printed at the bottom. I haven't seen a sample of this yet but I wanted to run this by you guys and see if this code makes sense.
function() {
NumberFormat nf = new DecimalFormat("#,##0.00");
double total = 0D;
for (...) {
double d = Math.random();
total += round(d);
print(nf.format(d));
print(nf.format(total));
double round(double d) {
return (double)(Math.round(d*100)/100D);
}Is my round() sound?I have a user who is complaining that the numbers on
her report don't add up to the total that's printed at
the bottom. This could be a problem with the user in that they don't understand numerics.
Or it could b a problem with you in that you do not understand the problem domain.
Floating point numbers are always inaccurate. It doesn't matter whether humans or computers do this. That is because floating point numbers (when used correctly) are an approximate measure of something which can not be measured exactly.
For example a pound of hamburger might be marked as weighing 1.01 pounds. The inaccuracy is in that it might actually weigh 1.01015678 pounds (but is unlikely to weigh even that.) There is no way to get the exact weight.
Now if that is your situation then it is problem with the user - the user doesn't understand numerics and the inherit inaccuracies.
And it would probably be a bad idea for you to "fix" it for one user, when other users are expecting correct approximations.
(One way to fix this is to 'fiddle' with the numbers that make up your sum. Adjust one so everything 'looks' right.)
On the other hand maybe it is your problem. For example money. Money is not a floating point number, because money is always exact. Even when caculating interest it is always exact. You will never end up with a partial penny in your savings account, no matter how the interest rate is computed.
And since money is accurate a floating point number is not necessarily the best way to represent it. Care must be used in doing so. As a previous poster suggested the BigDecimal class can be used.
Or if your numbers are small then simply convert the money to integers by multiplying by 100 and rounding and then compute everything using that. And simply reformat the integer values so they look like floating point numbers rather than integers when you print them out. -
I have searched, but I cannot seem to find an answer to my question.
I am a student in into to programing and I am trying to figure out why my decimals will not round. I have tried everything I can find, but being new to java programing, I am sure I am making a syntatical error somewhere. My program works other than not displaying the decimal places the way I want, 200.00 not 200.0.
The following is my code, I have commented out each of the decimal formats I have tried.
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class CheckingAcct
//int decimalPlaces = 2;
// Truncates the big decimal value.
//bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_DOWN);
//String string = bd.toString();
//DecimalFormat df = new DecimalFormat ( "0.0#" );
//DecimalFormat twoDigits = new DecimalFormat ( "0.0#" );
//DecimalFormat decimalFormat = (DecimalFormat)numberFormat;
//decimalFormat.applyPattern("0.0#");
public static void main (String args[])
String strBalance,
strDeposit,
strChecks;
double balance = 200.00,
deposit,
lbcharge = 2.00,
nsfcharge = 25.00,
checks;
//Display Starting Balance
JOptionPane.showMessageDialog (null, "Your current balance is:$" + balance);
//calculate balance
strDeposit = JOptionPane.showInputDialog ("Please enter your deposit amount:$");
deposit = Double.parseDouble (strDeposit);
balance = deposit + balance;
JOptionPane.showMessageDialog (null, "Your current balance after deposit is:$" + balance);
strChecks = JOptionPane.showInputDialog ("Please enter the total amount of checks written:$");
checks = Double.parseDouble (strChecks);
balance = balance - checks;
//Low Balance
if (balance < 100.00)
JOptionPane.showMessageDialog (null, "You have fallen below the minium required balance and you have been charged:$" + lbcharge);
balance = balance - lbcharge;
else
lbcharge = 0.00;
//NSF Charge
if (balance <= 0.00)
JOptionPane.showMessageDialog (null, "You have a negative balance and you have been charged:$" + nsfcharge);
balance = (balance - nsfcharge);
JOptionPane.showMessageDialog (null, "Your current balance is:$" + balance);
else
JOptionPane.showMessageDialog (null, "Your balance is:$" + balance);
System.exit (0);
}I tend to use super class NumberFormat, because I can
never remember the jiggery-pokery of those patterns:
import java.text.*;
public class Example {
public static void main(String[] args) {
NumberFormat fmt = NumberFormat.getInstance();
fmt.setMinimumFractionDigits(2);
fmt.setMaximumFractionDigits(2);
System.out.println(fmt.format(200.0));
System.out.println(fmt.format(200.115));
System.out.println(fmt.format(200.125));
}Just be aware that NumberFormat/DecimalFormat uses
half-even rounding.This confirms another thought I had, that I must format each number I want to use. Thank you. -
How to round numbers in RTF templates?
Hello!
I'm using BI Publisher for Word (Oracle BI Publisher Builder for Word 10.1.3.4.1) to build a template to my BI Publisher report and I want to calculate this:
avg(X)/(avg(Y)-avg(Z)/0.9)
The result should be rounded to 3 places.
I tried:
<?(sum(X) div count(X)) div ((sum(Y) div count(Y)) - (sum(Z) div count(Z)) div 0.9)?>
and I obtained the expected result.
But, when I try to round in this way:
<?xdofx:round((sum(X) div count(X)) div ((sum(Y) div count(Y))-(sum(Z) div count(Z)) div 0.9),3)?>
I obtain 0 when is expected other value.
Can someone help me?Hi ,
You can select the number format in RTF template .Double click the Form Field select
Type :Number
Number Format :#,##0.000
Thanks.
Maybe you are looking for
-
I migrated all of my photos from my PC to my mac but I can't find them on my laptop!?
Hi I hope someone can help me. It took hours on end to successfully migrate my photos and documents from my Windows PC to my new MacBook. (I'm a professional photographer) When The Migration Assistant was completed, I closed the window and went to my
-
White screen computer will not boot up
computer starts up to the white screen with the gary apple and spins that's all it does
-
Toolbox - how to turn off automatic backup warning?
How can I stop to toolbox from warning me that my automatic backups are not turned on? I prefer to backup when I need to. Thanks. Michael Moderator Note: Edited subject to match content.
-
SCCM 2012 R2 - WindowsUpdate.log showing error 0x80240037
Hi, Setup details: 1) OS: Windows 2012 R2 2) SCCM version: SCCM 2012 R2 with SUP role (WSUS v6.3.9600.16384) 3) SQL: SQL 2012 All the above resides on a single machine. Error description: Windows 2012 R2 Server clients are not reporting back to the s
-
Significance of async-enabled option of jms-messaging-bridge
Hi Folks !! I have a question regarding JMS-MESSAGING-BRIDGES: What difference will async-enabled = true | false will make to the bridge? Which option will be good from performance point of view ? Thanks in advance. Edited by: 994778 on Mar 19, 2013