# Truncation

R Mannam
Greenhorn
Posts: 7
I have a problem in generating the output for java code.

This is the excerpt of the code:
double x1=10.656;
double x2=14.8;
double x3=14.542;
double x4=10.0;
double x5=x1+x2+x3+x4;

The output is displayed as 49.99800000000005
My required output is 49.99800

Ben Souther
Sheriff
Posts: 13411
R Mannam
Welcome to JavaRanch!

In an effort to help you get the most from our forums, we've compiled a
list of tips for asking questions here. You can find the list in our
FAQ section here.

I'll move this thread to the Java In General (Beginner) forum for you.
Again, welcome to JavaRanch and good luck with your question.
-Ben

Campbell Ritchie
Sheriff
Posts: 50289
80
It all depends whether you are using J5 or not.
In J5, you can use the % tags, which you will find in the API description of the Formatter class. For example %.2f will print a floating-point number with two figures after the decimal point.

Before J5, you would have to use the NumberFormat and DecimalFormat classes.

R Mannam
Greenhorn
Posts: 7
Campbell! Thank you for your suggestion. I am utilizing JDK 1.4.1 in this project. I have tried using NumberFormat and DecimalFormat classes which you mentioned but could not be able to get desired results. Please explain clearly on how to apply these classes to my code. Thanks a lot.

This is my code:

import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.util.Locale;
class C{
public static void main(String args[]){
double x1=10.333;
double x2=23.56666;
DecimalFormat x3 = new DecimalFormat("####.000");
//NumberFormat x3 =NumberFormat.getInstance();
x3=(x1+x2);
System.out.println(x3);
System.out.println(x3.format(1234.56));
//System.out.println(x3.format(1234.56));

}
}

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15495
43
A DecimalFormat object is not something that represents a number. If x1 and x2 are doubles, and x3 is a DecimalFormat object as in your code above, the line:

x3 = (x1 + x2);

will ofcourse not work. The DecimalFormat object is an object that you use to format a number (in a variable of type double, for example) into text. To do that, you use the format(...) method of the object.

R Mannam
Greenhorn
Posts: 7
Jesper!

Thank you so much for your help. I was able to solve the issue.