Formatting a double
Hello,
I have a problem with formatting a double.
Suppose we have a double:
double x = 25.665478962
I want to round this to a double with 2 decimals:
thus: x has to be 25.67
How can I do this???
Thanks,
Daniel
Hi Daniel,
Do you know about the classes "java.text.DecimalFormat" and "java.lang.Math"? Are they not suitable for you? Have you seen this:
http://java.sun.com/docs/books/tutorial/java/data/numbers.html
Hope this helps you.
Good Luck,
Avi.
Similar Messages
-
How can I format the double value?
Hi,
I am trying to format the double variable as like,
double var = 1234.56789
but i want that variable as like var = 1234.56
How can i do that in java?
Please help me.
From
Parshuram WalunjkarTry something like the following, assume the variable 'd' underneath is your double value that you want to format.
double d = 4.45678;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(5);
nf.setMinimumFractionDigits(5);
String number = nf.format(d);
Then use the string "number" for printing out. -
Formatting a Double to 2 decimal places without first converting to String
Hi,
Does anyone have any clear idea on how to format a Double directly without first converting it
to a String.I have just read through DecimalFormat/NumberFormat but I think there might be an easier way.I am also aware of printf(%f) and format(%f),but unfortunately am using Java 1.4 at the moment which does not seem to support them(will upgrade soon).The code I have is as follows:
public void displayAnalysis ()
System.out.println ("========================================================================");
System.out.println ("========================================================================");
System.out.println ("\nANALYSIS RESULTS FOR FILE " + inputFile + " \n");
System.out.println ("========================================================================");
System.out.println ("========================================================================");
System.out.println ("\nString length: "+ inputText.length());
System.out.println ("Ratio of printing to non-printing characters: "+ pRatio);
System.out.println ("Ratio of vowels to consonants: "+ vRatio);
System.out.println ("");
System.out.println ("Frequency of vowels as a percentage of number of printing characters;");
System.out.println ("Percentage of a's ="+ (NumberFormat.format(new DecimalFormat(((double)frequency[0]*100)/printable)))));
System.out.println ("Percentage of e's ="+ ((double)frequency[1]*100)/printable + "%");
System.out.println ("Percentage of i's ="+ ((double)frequency[2]*100)/printable + "%");
System.out.println ("Percentage of o's ="+ ((double)frequency[3]*100)/printable + "%");
System.out.println ("Percentage of u's ="+ ((double)frequency[4]*100)/printable + "%");
System.out.println ("Number of whitespace characters were " + whitespace);
System.out.println ("");
System.out.println ("========================================================================");
System.out.println ("========================================================================");
System.out.println ("");
System.out.println ("");
}I would like to display the frequencies to 2 decimal places.As a last resort I will have to alter the code to use DecimalFormat,but I'm hoping someone has a simpler solution.Oops,please ignore the line for the first frequency (a's),I was just playing around with trying to use NumberFormat!
-
Formatting custum double precision
I don't understand the DecimalFormat API.
I need to format double variables trajectory_angle, velocity_fps and elapsed_time to three decimal place precision round off in the following code segment. For example, the value of elapsed_time would change from 1234.56789 to 1234.568 in results_string. Note that I need to set this precision only in this method since I wish to retain prior precision determined in other parts of the code prior to this method being invoked. Please examine this segment and indicate what corrections I need to make.
public String results()
DecimalFormat df = new DecimalFormat(.###);
results_string =
"Distance =\t\t" + distance / 5280.0 + " miles\n"
+ "Altitude =\t\t" + altitude + " feet\n"
+ "Trajectory Angle =\t" + df.format(trajectory_angle) + " degrees\n"
+ "Velocity =\t\t" + df.format(velocity_fps) + " feet per second\n"
+ "Elapsed Time =\t\t" + df.format(elapsed_time) + " seconds\n";
return results_string;Nevermind. I found the solution. However, I need to see better examples on how to use that API.
-
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;
} -
Hi,
I am looking for some help to format the output of this test app
the objective of this program is to work out the demonations of money required
to pay out a withdrawl.
The results seem to be what I want thanks to some help on this forum last week
only as I am using a double the output is printing wrong.
for example
amount 173 / 50 = 3.43
so there are three $50's in 173
the remainder is 23
so
23 / 20 = 1.15
so there is three $20 in 23
the remainder is 3
etc
I am happy that it is working out the right number of demonations required
but I cannot sort out the output.
Here is the code
package Exer2;
public class Exer3
{ // start class
public static void main(String args[])
{ // start main
double oldBal = 9526;
double newBal;
double withDraw = 173; // amount withdrawn
double remainder = 0;
double balance = 0;
// Set up the arrays and dim to 11
double [] arrayFive = new double [11];
double [] arrayPound = new double [11];
arrayFive [0] = 50;
arrayFive [1] = 20;
arrayFive [2] = 10;
arrayFive [3] = 5;
arrayFive [4] = 2;
arrayFive [5] = 1;
arrayFive [6] = 050;
arrayFive [7] = 020;
arrayFive [8] = 020;
arrayFive [9] = 005;
arrayFive [10] =001;
// Objective is to work out how many 50's , 20's 10's etc are required
// to pay out the withdrawl figure above
System.out.println("Amount Withdrawn : " + withDraw);
System.out.println("");
while ( withDraw > 0 )
{ // Start while loop
for ( int i = 0; i < 11; i++)
{ // start for loop
if (withDraw > 0 )
{ // start if statement
arrayPound = withDraw / arrayFive [i];
remainder = withDraw % arrayFive [i];
//System.out.println(" First print arrayPound [i] " + arrayPound [i]);
balance = arrayPound [i] * arrayFive [i];
withDraw = withDraw - balance;
withDraw = remainder;
//System.out.println(" Third print Arrayfive [i] " + arrayFive [i]);
//System.out.println(" Fourth print withdraw " + withDraw);
System.out.println("The Number of " + arrayFive [i] + " Pounds/coins is : " + arrayPound [i]);
System.out.println("");
System.out.println("Remainder : " + remainder );
System.out.println("");
} //end if statement
//else Do not need an else for this
//{ // start else
//System.out.println("Exiting....");
//System.exit(0);
//continue;
//return;
//break;
//} // end else
} // end for loop
} // end while loop
} // end main
} // end class
Here is the output
Amount Withdrawn : 173.0
The Number of 50.0 Pounds/coins is : 3.46
Remainder : 23.0
The Number of 20.0 Pounds/coins is : 1.15
Remainder : 3.0
The Number of 10.0 Pounds/coins is : 0.3
Remainder : 3.0
The Number of 5.0 Pounds/coins is : 0.6
Remainder : 3.0
The Number of 2.0 Pounds/coins is : 1.5
Remainder : 1.0
The Number of 1.0 Pounds/coins is : 1.0
Remainder : 0.0
Can anyone help me to format this output correctly so its like
The Number of 50.0 Pounds/coins is : 3
I'm sure there is a cleaner/better way to do this so any comments would be appreciated
Thanks
DFIf you don't want to use DecimalFormat, try casting to an int...
System.out.println("The Number of "
+ arrayFive[i]
+ " Pounds/coins is : "
+ (int) arrayPound); -
Hello!
I have nr i double like this.. 1.2345
now I want only two digit accuracy, ie 1.23 and i want it correctly roundned. How do I do this. Ive tried with DecimalNumberFormat but get the answer in 1,23 wich is no good..because i cannot turn it back to a double.
Best Regards
DanielIf you want to have '.' as decimal separator use Locale.US
You can also use the DecimalFormat and pass the Constructor
the DecimalFormatSymbols to be used.
For parsing string use the parse method of NumberFormat.
it uses the correct DecimalFormatSymbols when the string is parsed.
double d = 1.2345d;
double parsedValue;
NumberFormat myFormat= NumberFormat.getInstance(Locale.US);
myFormat.setMimimumFractionDigits(2);
myFormat.setMaximumFractionDigits(2);
System.out.println(myFormat.format(d));
parsedValue = myFormat.parse( myFormat.format(d) ).doubleValue(); -
How to format a double to a certain precision?
Hi,
I have a variable of type 'double' and it's set to something like 2.3934583729. I was trying to print the double out to some standard system output with 2 decimal place, formatted precision, "2.39". It seems to me that there is no function like printf(".2f", var) in C/C++ that does the trick. Or am I overlooking something?
Any help would be greatly appreciated. Thanks.
AaronYes you are over looking something.
Check this out...
import java.text.*;
public class TwoDigits
public static final void main(String[] args) throws Exception
double aDouble = 2.3934583729;
DecimalFormat formatter = new DecimalFormat("#.00");
System.out.println(" aDouble : " + formatter.format(aDouble)); -
Help needed : Formatting a double using Decimal Format
Hi Everyone,
I am having trouble formatting doubles. Basically I recieve a double and an int that represents the number of decimal places.
From this I have to round the double. This is no problem, and is carried out as follows:
public static String roundDouble(double d, int scale){
BigDecimal big_decimal = new BigDecimal(d);
java.text.DecimalFormat formatter = new java.text.DecimalFormat();
formatter.applyPattern("########.#######");
double dubble = big_decimal.setScale(scale,BigDecimal.ROUND_HALF_UP).doubleValue();
return formatter.format(dubble,new StringBuffer(),new java.text.FieldPosition(formatter.FRACTION_FIELD)).toString();
This work fine for me. (I use a DecimalFormatter to convert exponential in to actual). However my problem is that when my colleuge uses this method from a different locale it all goes wonky.
In my locale of UK given something like 0.92742999999999 with 4 dp I get
0.9274. In his locale which is Germany, he gets 0,9274.0000
I assume I need to use DecimalFormatter.applyLocalizedPattern, but what should the pattern be?
regards,
dr_n35sformatter.applyPattern("########.#######");# before the decimal point have no effect on the format.
This work fine for me. (I use a DecimalFormatter to
convert exponential in to actual). However my problem
is that when my colleuge uses this method from a
different locale it all goes wonky.
In my locale of UK given something like
0.92742999999999 with 4 dp I get
0.9274. In his locale which is Germany, he gets
0,9274.0000The pattern for the UK should be ".#######"
The pattern for DE should be ",#######"
I assume I need to use
DecimalFormatter.applyLocalizedPattern, but what
should the pattern be?You can't hard code values into your code, use a properties file to localize your program. -
Hi friends,
I get a value from database using resultset.getString("amount");
Type of this "amount" field is double and on my jsp page it looks like 7,12800000000000E+008 this
what I need is to see on jsp page is like this " %7,12 " , how can I do this??You will be wanting the number formatting functions then.
Check out java.text.NumberFormat.
It provides formatting for numbers, currencies, percentages etc.
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
String sNum = nf.format(amount);
For JSP pages, JSTL provides wrapper tags for these function so you don't have to use scriptlets. You might want to check that out.
<fmt:formatNumber var="${amount}" minFractionDigits="2" maxFractionDigits="2"/>
Cheers,
evnafets -
Re: Formatting a double data type
See: http://javaalmanac.com/egs/java.text/FormatNum.html
thnx, that solved my problem, But gave rise to another.
When i have to display the result, I need in this format ##.00.
This works fine for non zero values after the decimal point. If i ahve
double d = 6.10;
NumberFormat format = NumberFormat.getNumberInstance();
System.out.println(format.format(d));
The ideally i need it to display: 6.10, but it display only 6.1.
I tried DecimalFormat too.. but couldnt find a solution. Please help. -
Format number of digit for a double value
Hello all
How I can format a double value so that there are only 2 values after the dot.
For example
2.332332 -> 2.33
3.1 -> 3.10
Thank you for your help
shuhuYeah, I keep forgetting about printf but if you are stuck with < 1.5 you have to go with DecimalFormat.
-
I need to format a double value without any precision
It can have 13 digits to the left of decimal and 6 digits right side of decimal.
I used
public static String formatDouble(double dNumber) {
DecimalFormat dcf = new DecimalFormat("##################0.000000");
String sformattedDouble = dcf.format(dNumber);
return sformattedDouble;
Now the problem is that the DecimalFormat class uses ROUND_HALF_EVEN rounding, which I do not want to use.Should I be using some other data type(like BigDecimal) instead as the numbers I am dealing with are pertaining to currency values so I can not use precision ?
Any suggestion will be great.Sorry I meant.....I do not want it to be rounded off
e.g. If I use it in following way I get
999999999999.000000 as output
public static void main(String args[]) {
double dbl = 999 999 999 998.999 999;
System.out.println(formatDouble(dbl));
You are trying to place a number with 18 decimal places in a double which only hold about 17 decimal places so the conversion to 999999999999 get done before you try to use it. If you realy need this sort of precision then you could try BigDecimal but be prepared for a big performance penalty. -
Jtree, Double Click to open a file
Here is what I have so far:
tree.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent evt){
if (evt.getClickCount()==2){
TreePath tp = tree
.getClosestPathForLocation(evt.getX(), evt.getY());
File file = (File)tp.getLastPathComponent();
// open the file here
if(file.isFile() && file.exists()){
System.out.format("You double clicked %s", file.toString());
//---->What goes here?
});I've searched the internet and found a few examples that don't work. Anyhow if a person clicks on an image, it should open the image, if they click on a txt document it should open the text document. Any clues on how to implement that would be fantastic.Thanks that seems to work. I can open .txt documents without a problem. However images don't open and .html pages open and then immediately close. Any ideas?
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;.
tree.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent evt){
if (evt.getClickCount()==2){
TreePath tp = tree
.getClosestPathForLocation(evt.getX(), evt.getY());
File file = (File)tp.getLastPathComponent();
// open the file here
if(file.isFile() && file.exists()){
System.out.format("You double clicked %s", file.toString());
try {
Desktop.getDesktop().open(file);
} catch (IOException ex) {
System.out.println("File Error: Unable to open");
Logger.getLogger(FileTree.class.getName()).log(Level.SEVERE, null, ex);
}); -
Need help with formating numbers
public void returnDollars()
double dollar;
dollar=amountr-amount;
NumberFormat fmt = NumberFormat.getNumberInstance();
System.out.println(fmt.fomat(dollar));
there is my code.....now lets say
amountr = 10
amount 8.5
now when i print my dollar amount i want it to show up as 1 not 1.5 or 2. So in other words format it with no decimals and not round up at the same time.
Help would be appriciated...thankswell...after 8 hours of trying to get it working i did it.....here it is ...........I'm sure there are many ways to make it smaller.
import java.text.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Cashier
double amount;
double amountr;
double dollar;
double amountleft;
double quaters;
double test;
double dimes;
double pennies;
public void getAmount()throws IOException
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter amount due:");
String input = console.readLine();
amount = Double.parseDouble(input);
System.out.println("Amount due = " + amount);
public void recieve()throws IOException
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter amount recieved :");
String input = console.readLine();
amountr = Double.parseDouble(input);
System.out.println("Amount recieved = " + amountr);
public void returnDollars()throws IOException
double check = amountr-amount;
dollar=amountr-amount;
DecimalFormat fmt = new DecimalFormat("##");
String s = fmt.format((double)(long)dollar);
double d = Double.valueOf(s).doubleValue();
amountleft=check-d;
System.out.println("Dollars to return " + s);
public void returnQuaters()
quaters= amountleft/.25;
double check = quaters;
DecimalFormat fmt = new DecimalFormat("##");
String s = fmt.format((double)(long)quaters);
double d = Double.valueOf(s).doubleValue();
fmt.setMaximumFractionDigits(2);
String dol = fmt.format(amountleft);
//System.out.println(dol);
double e =Double.valueOf(dol).doubleValue();
e= e-2*(.25);
amountleft=e;
System.out.println("Quaters to return: " + s);
public void returnDimes()
dimes= amountleft/.1;
double check = dimes;
DecimalFormat fmt = new DecimalFormat("##");
String s = fmt.format((double)(long)dimes);
System.out.println("Dimes to return: " + s);
double d = Double.valueOf(s).doubleValue();
fmt.setMaximumFractionDigits(2);
String dol = fmt.format(amountleft);
double e =Double.valueOf(dol).doubleValue();
e= e-1*(.1);
fmt.setMaximumFractionDigits(2);
String dola = fmt.format(e);
double t =Double.valueOf(dola).doubleValue();
amountleft=t;
public void returnNickles()
double nickles = amountleft/.05;
double check = nickles;
DecimalFormat fmt = new DecimalFormat("##");
String s = fmt.format((double)(long)nickles);
System.out.println("Niclkles to return: " + s);
double d = Double.valueOf(s).doubleValue();
fmt.setMaximumFractionDigits(2);
String dol = fmt.format(amountleft);
double e =Double.valueOf(dol).doubleValue();
e= e-1*(.05);
fmt.setMaximumFractionDigits(2);
String dola = fmt.format(e);
double t =Double.valueOf(dola).doubleValue();
amountleft=t;
public void returnPennies()
double pennies = amountleft/.01;
DecimalFormat fmt = new DecimalFormat("##");
String s = fmt.format((double)(long)pennies);
System.out.println("Pennies to return: " + s);
public static void main(String[] a) throws IOException
Cashier cash = new Cashier();
cash.getAmount();
cash.recieve();
cash.returnDollars();
cash.returnQuaters();
cash.returnDimes();
cash.returnNickles();
cash.returnPennies();
Maybe you are looking for
-
Masking Certain Field in Vendor Master Data
We have a Enhancement which involves conversion of Vendor Numbers.,It so happened that a category of Vendor Codes were the Social Security Numbers. Now that due to Privacy Laws etc they are converting that number logic which is throwing challanges. T
-
Have not even been able to setup Mac mini due to no display on monitor. Attempting to use a Viewsonic VG2030vm monitor via DVI connector - out of box. Not work. Read about needing DVI-D cable and got one today from Apple. Same message on monitor d
-
HT3775 how can I use this codes? and Where?
I am trying to watch a Trailer for leapPad2 and I can't. It's showing me a massage that I need a special software for that and for more information press TELL ME MORE. When I do that it just showing me some codes. I don't know what should I do with t
-
Cache refresh of single object interferes with normal message processing
Hi When we do an update of an object in Integration Directory and activate change list AND a message (from a different scenario) is processed through Integration Engine at the same time, the message fails with "No RFC authorization for user <USER>" +
-
Hi ALL, I have to develop a customizing report for workflow. This report displays the status of the workflow and Agent Id with whom the workflow is currently pending. Something Similar to Tcode : SWI1 can anyone tell me if there is any function mo