Force 2 decimal places with java.text.DecimalFormat
Hi all,
I am trying to force 2 decimal places for sum of 2 doubles (please see my code below). According to the API javadoc this should always display 2 decimals, however at the moment if the second decimal is zero it gets chopped off:(
Any ideas what is going wrong?
Thanks,
Olli
public double sum(double valueOne,double valueTwo)
double sum=valueOne+valueTwo;
DecimalFormat forceDecimals=new DecimalFormat("0.00");
total=Double.parseDouble(forceDecimals.format(sum));
return sum;
}
Hi Olli,
you return sum and not total, but nevertheless returning a double doesn't help as 5.00 will always be 5.0.
An option would be to return the formatted String.
Similar Messages
-
Rounding problem with java.text.DecimalFormat
I see that the bug reported in relation to this (#4763975) has been closed.
I'm just wondering when will this bug be fixed or is it even scheduled to be fixed in the future?Hi Olli,
you return sum and not total, but nevertheless returning a double doesn't help as 5.00 will always be 5.0.
An option would be to return the formatted String. -
Please Suggest - new java.text.DecimalFormat Question
table2.setValueAt(
"$"+new java.text.DecimalFormat("#.##").format
((Double.valueOf(table2.getValueAt(row,1).toString())).doubleValue())*
((Double.valueOf(table2.getValueAt(row,2).toString())).doubleValue())
row,
3
);Is there a way to force DecimalFormat to display .00?
Is there a way to ignore a "$" preceding the value from table2.getValueAt(row,1)?Is there a way to force DecimalFormat to display .00?YES: new java.text.DecimalFormat("\u00A40.00").format
-
Java.text.DecimalFormat Error
I have this import directive in my jsp page.
<%@ page import="java.io.*,java.sql.*;java.text.DecimalFormat" contentType="text/html;charset=windows-1252"%>
I am using Jdeveloper 9i 9.0.3.
When I compile this page from within JDeveloper I get this error for java.text.DecimalFormat
Error: 'class' or 'interface' expected
When I compile outside JDeveloper, I get NO error.
Can somebody tell me what the problem is.<%@ page import="java.io.*;java.sql.*;java.text.DecimalFormat" contentType="text/html;charset=windows-1252"%>
I think that missing semi-colon is what's creating problems for you.
Sergio Bastos -
Java.text.DecimalFormat is parsing '22.3.6' !
I'm using DecimalFormat to mask a data entry field.
When I enter something like 22.3.6, it parses!
String docString = "22.3.6";
NumberFormat nFormat = new DecimalFormat();
float value = nFormat.parse(docString).floatValue();
System.err.println("value: " + value);
Gives me:
value: 22.3
I was expecting a NumberFormatException.
I'm running
build 1.5.0_05-b05
Should I enter this as a bug?I tried yout code and it formats the String the way you wanted:
public class Test
public static void main ( String[] args )
java.text.DecimalFormat df2 = new java.text.DecimalFormat("###########0.00");
System.out.println(df2.format(java.lang.Float.parseFloat("-3.0")));
} //End Main
} -
Java.text.DecimalFormat
hi folks,
I'm trying to format a floating point number so that it has exactly two digits after the decimal
DecimalFormat df=new DecimalFormat("##.00");
System.err.println(df.format(12.995));
My desired output is 12.99(truncation, no rounding)
the actual output is 13.00 (rounding)
how do I acheive what I what?
thank you!!Since DecimalFormat uses ROUND_HALF_EVEN, you need to use something else. The java.math.BigDecimal class is something you could use:
double value = 12.995;
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
System.err.println(bd); This would print out 12.99. -
Please help with java.text.MessageFormat...
Hi all
I'm reasonably new to java and have been struggling with this one for a while. I wonder if anyone can help?
The following code...
Object[] testArgs = {new Long(1273), "MyDisk"};
MessageFormat form = new MessageFormat(
"The disk \"{1}\" contains {0} file(s).");
System.out.println(form.format(testArgs));
...gives the following output...
The disk "MyDisk" contains 1,273 file(s).
I simply want to get rid of the comma, so that the output becomes...
The disk "MyDisk" contains 1273 file(s).
Any ideas? Many thanks for reading my thread and for any help you may be able to offer!
Kind Regards
Joncontains {0,number,#} file(s).
-
Help!printing float values with two decimal places
hi there java pips! im a newbie to this technology so forgive me for this really stupid question....i would like to perform mathematical operations on two float values....the problem is i want to print them in a standard format and that is i want them to be displayed with two decimal places (e.g 190.00, 12,72, 1,000.01) how can i do this?
Try java.text.DecimalFormat
NumberFormat nf = new DecimalFormat("0.00");
System.out.println(nf.format(x)); -
!!!! How to maintain the value with 2 decimal places !!!
hi
i have a double var and i need to maintain it with 2 decimal places only..
thanks..What do you mean with you need to "maintain it" with 2 decimal places?
Do you want to display the number with 2 decimal places? If so, have a look at the API documentation of java.text.DecimalFormat.
double d = 3.14159265358979;
NumberFormat f = new DecimalFormat("0.00");
System.out.println(f.format(d)); -
I need help with setting 2 decimal places
I am using netbeans to create a GUI. My math works I need help formatting the result to 2 decimal places.
Thanks for any help.
This is part of my code..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// Regular button
double RegularPrice = 3.09;
double num1, result;
num1 = Float.parseFloat(jTextField1.getText());
result=RegularPrice * num1;
jLabel2.setText(String.valueOf(result));
}http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html
-
Help with java (2 simple classes)
would anyone be able to help me with some questions about two very short java classes?
i have come up with some answers of my own, but yeah, i'm not sure how correct my answers are....
the 4 questions are:
1. The data attributes m, n and grid in the HeatGrid class are declared private, and methods
such as gridHeight(), gridWidth() and copyGrid() are provided to extract their value. Why
is the better class design than simply declaring those attributes as public?
My answer: So other classes accessing them cannot modify those data atributes, i am not sure why this is better class design.
2. Why must the (global) constants in HeatSim.java be declared static ?
My Answer: because HeatSim is what you run first and so you don't create a HeatSim object, you just access its methods, thus the need to make them static.
3. Assuming HeatGrid has been fully implemented, during the execution of the statement
HeatGrid = new HeatGrid(inGridFile), how many objects of HeatGrid, double [][] and
Scanner are created?
My Answer: 1 HeatGrid object, 1 doulbe[][] object and 1 scanner object
Which of these objects must still exist after the statement completes execution?
4. For each of the classes HeatSim and HeatGrid, identify the client and supplier classes
(including library classes).
My Answer: So far this is what i have done. for the HeatSim class, i said that the supplier classea are:
double
int
boolean
String
Math Class
viewgrid class
array
and the clients for the HeatSim class are:
HeatGrid class
if anyone can help me i will but up the VERY short code to these two classes. I am really stuck and any help woould be greatly appriciated! :)
Lots o love
Sarahok here is the code (i don't have my compelted copy on me but this will do for the moment).....
import java.lang.Integer;
import java.lang.Double;
import java.text.DecimalFormat;
public class HeatSim {
final static boolean ENABLE_VIEW = true; // if true, create GUI to view grid
final static double DEFAULT_THR = 1.0e-02;
final static int DEFAULT_PAUSE = 100; // pause between each update of window in ms
final static int DISPLAY_WIDTH = 7; // width to print each grid value
final static int MAX_MN_DISPLAY = 10; // maximum grid size to be displayed
public static void main(String[] args) {
// initialize program `parameters' according to the command line,
// entering `default' values if none were given
String inGridFile = (args.length < 1)? "": args[0];
int nIter = (args.length < 2)? 1: Integer.parseInt(args[1]);
double Thr = (args.length < 3)? DEFAULT_THR: Double.parseDouble(args[2]);
String dumpFile = (args.length < 4)? "": args[3];
DecimalFormat residFormat = new DecimalFormat("0.00E0");
ViewGrid view = null;
System.out.println("HeatFlow simulation program");
if (inGridFile.equals("")) {
System.out.println("Error: an empty grid file name was entered");
return;
// create HeatGrid object
HeatGrid heatGrid = new HeatGrid(inGridFile);
int m = heatGrid.gridHeight();
int n = heatGrid.gridWidth();
if (m <= MAX_MN_DISPLAY && n <= MAX_MN_DISPLAY) {
System.out.println("\nGrid at time 0:" );
heatGrid.display(DISPLAY_WIDTH);
if (ENABLE_VIEW) {
// create a ViewGrid WINDOW object to view the grid
view = new ViewGrid(m+2, n+2, DEFAULT_PAUSE);
view.display(heatGrid.time(), 0.0, heatGrid.copyGrid());
while (heatGrid.time() != nIter && heatGrid.residual() > Thr) {
heatGrid.iterate();
if (m <= MAX_MN_DISPLAY && n <= MAX_MN_DISPLAY) {
System.out.println("Grid at time " + heatGrid.time() +
" has residual " +
residFormat.format(heatGrid.residual()));
heatGrid.display(DISPLAY_WIDTH);
if (ENABLE_VIEW) {
view.display(heatGrid.time(), heatGrid.residual(),
heatGrid.copyGrid());
} //while(...)
if (ENABLE_VIEW) {
view.finalize();
if (!dumpFile.equals("")) {
heatGrid.dumpGrid(dumpFile);
System.out.println("\nHeat Flow simulation of (" + m + "+2)x(" + n +
"+2) grid ends at time " + heatGrid.time() +
" with residual " +
residFormat.format(heatGrid.residual()));
} //mainProgram()
} //HeatSim
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class HeatGrid {
private int m, n;
private double[][] grid; // m+2 x n+2 array representing a grid
private int t; // the time the grid has been evolved
private double resid; // residual left from the last timestep
// initializes m, n and grid according to the information in the grid file
// of name gridFileN; sets t to 0, and resid to Double.MAX_VALUE
public HeatGrid(String gridFileN) {
} //HeatGrid()
// returns the value of m
public int gridHeight() {
return 0; // [ replace with an appropriate value ]
} //gridHeight()
// returns the value of n
public int gridWidth() {
return 0; // [ replace with an appropriate value ] =
} //gridWidth()
// returns the value of t
public int time() {
return 0; // [ replace with an appropriate value ]
} //time()
// returns the value of the residual from the previous timestep
public double residual() {
return 0; // [ replace with an appropriate value ]
} //residual()
// returns a copy of the grid
public double[][] copyGrid() {
return null; // [ replace with an appropriate value ]
} //copyGrid
// precondition: all elements of grid can be printed to 1 decimal place
// using width characters.
// prints the m+2 x n+2 grid by rows, rows in descending order.
// All values are printed to 1 decimal place, and are right-justified
// in a text field of width characters.
// Note: this method is for debugging; hence right-justification is useful
public void display(int width) {
} //display()
// advance the simulation a single timestep
public void iterate() {
} //iterate()
// prints the m+2 x n+2 grid by rows, rows in ascending order.
// All values are printed to 2 decimal places, with at least one space
// between them.
// Note: this method is intended for result checking by a computer program;
// thus justification is not important.
public void dumpGrid(String outGridFileN) {
} //dumpGrid -
like, right now i have this huge equation;
double heatIndex8 = (-42.379) + (2.04901523 * birmingTemp[7]) + (10.14333127 * birmingHum[7]) - (0.22475541 * (birmingTemp[7] * birmingHum[7])) -
(6.83783 * Math.pow(10, -3) * Math.pow(birmingTemp[7], 2)) - (5.481717 * Math.pow(10, -2) * Math.pow(birmingHum[7], 2)) +
(1.22874 * Math.pow(10, -3) * Math.pow(birmingTemp[7], 2) * birmingHum[7]) + (8.5282 * Math.pow(10, -4) * birmingTemp[7] * Math.pow(birmingHum[7], 2))
- (1.99 * Math.pow(10, -6) * Math.pow(birmingTemp[7], 2) * Math.pow(birmingHum[7], 2))and it prints out an insane amount of decimal places...
how can I tell the code to round(heatIndex8) to the tens place?paulcw wrote:
Use a java.text.DecimalFormat, or one of the printf methods that are now all over the place. (Well, String and java.io.PrintWriter and PrintStream, in particular).
By the way the size of the equation doesn't have a lot to do with it.
Edited by: paulcw on Feb 2, 2008 1:23 PMI know it doesn't, but I just really hate it.
decimal format you say? I'll go check that. -
Hello, i want to have my results in my shop apllication in two decimal places. I tried DecimalFormat f = new DecimalFormat("#.##"); with import java.text.DecimalFormat; but it doesnt change the decimal places.
And when i try this class example which i found on http://www.roseindia.net/java/beginners/RoundTwoDecimalPlaces.shtml it says that inner classes cannot have static declarations on public static void main(String[] args) { and public static float Round(float Rval, int Rpl) {
Im using netbeans 5,5, does someone know what the problem is?
public class RoundTwoDecimalPlaces{
public static void main(String[] args) {
float num = 2.954165f;
float round = Round(num,2);
System.out.println("Rounded data: " + round);
public static float Round(float Rval, int Rpl) {
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
Edited by: javaboy on Nov 11, 2007 12:46 PMpackage view;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import controller.index;
import model.product;
import java.text.*;
public class View_basket extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
private index index;
private JButton btnGoToPay;
private JLabel[] lblProducts, lblPrices;
private int countProducts;
private int offset=40; // # of pixels from the top
private int increment=20; // the next product will appear this amount of pixels below it's predecessor
private JPanel container;
public View_basket(index index){
this.container = new JPanel(null);
this.container.setName("Shopping basket");
this.container.setBackground(new Color(151, 186, 225));
this.container.setSize(190,200);
this.container.setLocation(550,20);
this.index=index;
public JPanel updateGui(){
System.out.println("class view.View_basket.updateGui()");
ArrayList products = index.basket.getProducts();
countProducts = products.size();
// if product basket is to big, resize the basket frame
if(countProducts > 6){
this.container.setSize(190,(300+((countProducts-6)*10)));
lblProducts = new JLabel[countProducts];
lblPrices = new JLabel[countProducts];
JLabel lblTitle = new JLabel();
lblTitle.setText("Winkelmand");
lblTitle.setBounds(5, 5, 150, 20);
lblTitle.setFont(index.FONT_12_BOLD);
this.container.add(lblTitle);
int teller=offset;
double total=0;
// walk trough all values from the arrayList
for(int i=0; i < countProducts; i++){
product product = (product)products.get(i);
lblProducts[i] = new JLabel(product.toString());
lblProducts.setBounds(5, teller, 130, 20);
lblProducts[i].setFont(index.FONT_10_PLAIN);
this.container.add(lblProducts[i]);
lblPrices[i] = new JLabel("? "+ product.getPrice());
lblPrices[i].setBounds(140, teller, 150, 20);
lblPrices[i].setFont(index.FONT_10_PLAIN);
this.container.add(lblPrices[i]);
teller +=increment;
total += product.getPrice();
// create total labels
JLabel lblTotal = new JLabel("Totaal: ");
lblTotal.setBounds(5, teller, 50, 20);
lblTotal.setFont(index.FONT_10_BOLD);
this.container.add(lblTotal);
// create total labelseeuro
JLabel lblTotalPriceeuro = new JLabel("? "+ total);
lblTotalPriceeuro.setBounds(140, teller, 50, 20);
lblTotalPriceeuro.setFont(index.FONT_10_BOLD);
this.container.add(lblTotalPriceeuro);
// create total labelsdollar
JLabel lblTotalPricedollar = new JLabel("$ "+ total*1.45);
lblTotalPricedollar.setBounds(140, teller, 50, 40);
lblTotalPricedollar.setFont(index.FONT_10_BOLD);
this.container.add(lblTotalPricedollar);
int btnOffset = this.container.getHeight()-25;
btnGoToPay = new JButton("Betalen...");
btnGoToPay.setBounds(5, btnOffset, 180, 20);
btnGoToPay.setFont(index.FONT_12_BOLD);
btnGoToPay.addActionListener( this );
if(countProducts == 0)
btnGoToPay.setEnabled(false);
this.container.add(btnGoToPay);
return container;
public void actionPerformed(ActionEvent event) {
// if the pay button is pressed
if(event.getSource().equals(btnGoToPay)){
((View_pay) index.panelPay).updateGui();
index.showPanel("View_pay"); -
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;
} -
Hi should be a pretty easy one but could someone help me display the Average in this line to one decimal place. I presume its done with math.round() but can't figure it out.
Thanks in advance
The line is:
<c:out value="${row.Average}"/>or seeing as you are using JSTL
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
//or <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> for Tomcat5
<fmt:formatNumber value= "${row.Average}" type="number" maxFractionDigits="1" />It uses the java.text.DecimalFormat class under the hood anyway :-)
Cheers,
evnafets
Maybe you are looking for
-
How can I test the Built in Camera is working
Hi Guys, I installed Windows 7 and everything seem to be working great! As for the built-in Camera, how would I test it, I can't see any Camera button under Computer as I alwasy used to see in Windows XP. Anyone could help? Solved! Go to Solution.
-
Two forms that update differrent tables on the same page?
I tried to add two forms that update different tables on to one page. Problem is when I do that the forms gives me an error saying the field does not exist. It's like it is trying to update one table with the other tables fields. As an example Say I
-
I'm using OS X 10.6.8 my airport utility isnt working
I just got a new airport/time capsule, when started set up it said my current airport utility was out of date i checked for softwear updates and didnt find that i needed one i search the apple site and found an updated airport utility and downloaded
-
my ipod touch 4th generation won't synch.i'm trying to put a pdf file on it.please help thanks in advance...
-
Make a purchased movie smaller
I bought an HD movie in iTunes. The file size is huge. Can I make it smaller to fit on my iPad without taking up all my memory?