# Why so many decimal points in my basic code?

Show 40 post(s) from this thread on one page
Page 1 of 2 12 Last
• October 28th, 2012, 05:20 PM
divebomb33
Why so many decimal points in my basic code?
A program I've been working on needs to calculate a number(salary), add a 10% commission to the salary and output to the user the total annual earnings. My programs gets those results, however the output shows unnecessary decimals to the final answer. I'm looking for something that looks like this 55000.00 as opposed to 55000.000000001. Can someone help me? Here's my code thus far-
Code java:

```import java.util.Scanner;   public class Commission{   public static void main (String[] args){ Scanner kb = new Scanner(System.in); Double a = 1.1, b, c;   System.out.println("What is your fixed salary?"); b = kb.nextDouble();   c = b * a;       System.out.println("Your fixed salary is \$" + b +" ");   System.out.println("With the current commission being 10% of total sales, your total annual compensation is \$" + c);   } }```
• October 28th, 2012, 05:24 PM
divebomb33
Re: Why so many decimal points in my basic code?
Also my output looks like this-
run:
50000
With the current commission being 10% of total sales, your total annual compensation is \$55000.00000000001
BUILD SUCCESSFUL (total time: 53 seconds)

I'd ideally like to make the fixed salary number look like \$50,000.00 instead of \$50000.0 and the total annual compensation look like \$55,000.00 instead of \$55000.00000000001. I'm very new at Java and would appreciate basic understandable feedback. Thanks
• October 28th, 2012, 06:29 PM
helloworld922
Re: Why so many decimal points in my basic code?
There are two things going on here. First is the way computers represent floating point numbers. There are several good articles on this topic, I'll link to one: What Every Computer Scientist Should Know About Floating Point Arithmetic.

The basic jist is your computer can't represent every possible floating point number, and since floating point numbers are a binary format the decimal equivalent representation taking into account these gaps can often-times really long decimals (such as the \$55000.00000000001 you're getting).

Now if you don't actually care about this difference in representation vs. what's displayed (the "close enough is good enough" approach) you can simply modify the way you display your output.

There are several ways to do this, the simplest method is to use the printf method.

Code java:

```double value = 123.1234567890123456789;   System.out.printf("Full computer representation: \$%.14f\n", value); System.out.printf("Default double precision display: \$%f\n", value); System.out.printf("Formatted to 2 decimal places: \$%.2f\n", value);```

```Full computer representation: \$123.12345678901235
Default double precision display: \$123.123457
Formatted to 2 decimal places: \$123.12```

This method works, but there's a much better way to accomplish this by using the NumberFormat and DecimalFormat classes. You can create your own format or you can ask Java to give the currency format for your current local.

Code java:

```NumberFormat format = new DecimalFormat(".00 USD"); NumberFormat local = NumberFormat.getCurrencyInstance(); System.out.println("My US dollar format: " + format.format(value)); System.out.println("My local currency format: " + local.format(value));```

```My US dollar format: 123.12 USD
The built-in currency formatter: \$123.12```

My local is currently in the US so it formats the currency as such. However, if you are in the UK it might give you the currency in Pounds, or you might get Yen in Japan, etc.
• October 28th, 2012, 07:05 PM
divebomb33
Re: Why so many decimal points in my basic code?
This looks extremely helpful. The only problem I'm having is where to place the code you described in conjunction with my code. Any help you could offer would be amazing!
• October 28th, 2012, 07:38 PM
Zaphod_b
Re: Why so many decimal points in my basic code?
Here's the thing: The author of Java made it "easy" to print out numerical values as long as you don't care what they look like. If you want to print floating point numbers formatted a certain way, then you have to do a little work. Not really very much work, thanks to a couple of formatting classes, but some work.

References:
NumberFormat

and

DecimalFormat

If you know that you want currency formatted like the U.S. (dollar sign, commas separating groups of three digits and a decimal point that is a period), and your installation has a US Locale as its default, you can try the following:

Code java:

` DecimalFormat formattedDollars= new DecimalFormat("\$#,##0.00");`

Then print a String with the desired dollar format with
Code java:

``` double price = whatever; . . . System.out.print("With DecimalFormat : Price = " + formattedDollars.format(price));```

For programs with a more international flavor (or is it flavour?), you can use NumberFormat set to a particular Locale. For example to print currency using German convention (periods separate groups of three digits, the "decimal point" is a comma, and it's followed by a euro sign), you could try something like the following:

Reference: Locale

Code java:

``` // Get currency format for specific Locale NumberFormat currencyGermany = NumberFormat.getCurrencyInstance(Locale.GERMANY);```

Then print your currency value with something like
Code java:

` System.out.print("With German NumberFormat: Price = " + currencyGermany.format(price));`

References:

I made a little program that added 10% handling charge to the basic price of goods and printed the results for a number of prices starting at 0.10:

The lines labelled "Without format" were printed the naive way, starting with
Code java:

` System.out.print("Without format : Price = \$" + price);`

For those statements, Java chooses a "generic" format that it deems reasonable, and the user doesn't have to worry about it, but the user has no control either.

Here's the output:
Code :

```Without format : Price = \$0.1, Total = \$0.11000000000000001 With DecimalFormat : Price = \$0.10, Total = \$0.11 With German NumberFormat: Price = 0,10 €, Total = 0,11 €   Without format : Price = \$1.1, Total = \$1.2100000000000002 With DecimalFormat : Price = \$1.10, Total = \$1.21 With German NumberFormat: Price = 1,10 €, Total = 1,21 €   Without format : Price = \$11.1, Total = \$12.21 With DecimalFormat : Price = \$11.10, Total = \$12.21 With German NumberFormat: Price = 11,10 €, Total = 12,21 €   Without format : Price = \$111.1, Total = \$122.21000000000001 With DecimalFormat : Price = \$111.10, Total = \$122.21 With German NumberFormat: Price = 111,10 €, Total = 122,21 €   Without format : Price = \$1111.1, Total = \$1222.21 With DecimalFormat : Price = \$1,111.10, Total = \$1,222.21 With German NumberFormat: Price = 1.111,10 €, Total = 1.222,21 €   Without format : Price = \$11111.1, Total = \$12222.210000000001 With DecimalFormat : Price = \$11,111.10, Total = \$12,222.21 With German NumberFormat: Price = 11.111,10 €, Total = 12.222,21 €   Without format : Price = \$111111.1, Total = \$122222.21000000002 With DecimalFormat : Price = \$111,111.10, Total = \$122,222.21 With German NumberFormat: Price = 111.111,10 €, Total = 122.222,21 €   Without format : Price = \$1111111.1, Total = \$1222222.2100000002 With DecimalFormat : Price = \$1,111,111.10, Total = \$1,222,222.21 With German NumberFormat: Price = 1.111.111,10 €, Total = 1.222.222,21 €   Without format : Price = \$1.11111111E7, Total = \$1.222222221E7 With DecimalFormat : Price = \$11,111,111.10, Total = \$12,222,222.21 With German NumberFormat: Price = 11.111.111,10 €, Total = 12.222.222,21 €```

The statements that define the DecimalFormat and the NumberFormat can appear (once) in the program block, anywhere before they are used in the print statements. (So, for example, if the values are being printed in main(), you can put the format definition statements at the beginning of main().)

Cheers!

Z
• October 28th, 2012, 07:46 PM
divebomb33
Re: Why so many decimal points in my basic code?
Can either of you show me how I incorporate your suggested code into what I already have in my first post? Thanks in advance!
• October 28th, 2012, 10:02 PM
helloworld922
Re: Why so many decimal points in my basic code?
If you don't want to type it out, just copy/paste the sample code we've provided into your program. You'll have to modify the code slightly to get it to display the message you want and change variable names, but there really should be plenty of information available here for you to experiment and test with until you get something that works how you want it to. Try it out and if you're still having troubles ask about those specific problems you're having.
• October 29th, 2012, 09:44 AM
divebomb33
Re: Why so many decimal points in my basic code?
The problem I'm having is each of you pointed out several techniques to help me get my desired results. I'm so new at this that I have no idea where the suggested code might go in conjunction to my initial code.
• October 29th, 2012, 09:45 AM
divebomb33
Re: Why so many decimal points in my basic code?
I've been trying to add the code mentioned but I'm struggling to put it in the right places.
• October 29th, 2012, 10:34 AM
helloworld922
Re: Why so many decimal points in my basic code?
Where have you tried putting the code? What does the compiler/program output tell you?
• October 29th, 2012, 10:40 AM
divebomb33
Re: Why so many decimal points in my basic code?
Here's what I tried recently-
Code java:

```import java.util.Scanner;     public class Commission{   public static void main (String[] args){ Scanner kb = new Scanner(System.in); double a = 1.1, b, c;     DecimalFormat formattedDollars= new DecimalFormat("\$#,##0.00"); double value = whatever;   System.out.println("What is your fixed salary?"); b = kb.nextDouble();   c = b * a;   System.out.print("With DecimalFormat : Value = " + formattedDollars.format(value)); System.out.println("Your fixed salary is \$" + b +" "); System.out.println("With the current commission being 10% of total sales," + "your total annual compensation is \$" + c);   } }```

I know I have to reconfigure my System.out code but I'm not sure where I'm screwing up here. The compiler gives me a runtime exception
• October 29th, 2012, 10:42 AM
divebomb33
Re: Why so many decimal points in my basic code?
I also found this link which looked helpful but again don't grasp where to put code like this with my code
Make cents with BigDecimal - JavaWorld
• October 29th, 2012, 10:58 AM
Zaphod_b
Re: Why so many decimal points in my basic code?
Quote:

Originally Posted by divebomb33
Here's what I tried recently
.
.
.
runtime exception

That code will not compile, so I can't see how it could be giving a runtime exception. For best chances of getting helpful responses with fewest iterations it is recommended to post the exact code that you are trying to use.

Cheers!

Z
• October 29th, 2012, 11:33 AM
divebomb33
Re: Why so many decimal points in my basic code?
Here is what I have so far that is fully functional. All I'd like to do is possibly add-
Code java:

```import java.text.DecimalFormat; import java.text.NumberFormat```
in conjunction with what I already have. My programs outputs results numbers with decimal points all over the place.
Here is what I have so far that is fully functional-

Code java:

```import java.util.Scanner;     public class Commission{   public static void main (String[] args){ Scanner kb = new Scanner(System.in); double a = 1.1, b, c;         System.out.println("What is your fixed salary?"); b = kb.nextDouble();   c = b * a;     System.out.println("Your fixed salary is \$" + b +" "); System.out.println("With the current commission being 10% of total sales," + "your total annual compensation is \$" + c);   } }```

I found this on site and think something similar would work with my program. Just confused where to put it and what variable to change-
Code java:

```package org.kodejava.example.text;   import java.text.DecimalFormat; import java.text.NumberFormat;   public class DecimalFormatExample { public static void main(String[] args) { // We have some millons money here that we'll format its look. double money = 100550000.75;   // By default to toString() method of the Double data type will print // the money value using a scientific number format as it is greater // than 10^7 (10,000,000.00). To be able to display the number without // scientific number format we can use java.text.DecimalFormat wich // is a sub class of java.text.NumberFormat.   // Below we create a formatter with a pattern of #0.00. The # symbol // means any number but leading zero will not be displayed. The 0 // symbol will display the remaining digit and will display as zero // if no digit is available. NumberFormat formatter = new DecimalFormat("#0.00");   // Print the number using scientific number format. System.out.println(money);   // Print the number using our defined decimal format pattern as above. System.out.println(formatter.format(money)); } }```
• October 29th, 2012, 12:26 PM
divebomb33
Re: Why so many decimal points in my basic code?
Any help guys?
• October 29th, 2012, 12:36 PM
Zaphod_b
Re: Why so many decimal points in my basic code?
Quote:

Originally Posted by divebomb33
...

I found this on site and think something similar would work with my program. Just confused...

As documented in the links that I gave in my first post:
The static format method of the NumberFormat returns a String. The static format method of the DecimalFormat classes returns a String.

"So what?" you say.

Well, you can use that String any way that you want to. You can put it in a print statement or whatever.

Question: In your last sample program, what does the following statement do?
Code java:

``` // Print the number using our defined decimal format pattern as above. System.out.println(formatter.format(money));```
Answer: Prints the numerical value as a String according to the formatter definition, right?

Next Question: What does the following statement do?
Code java:

` System.out.println("money = \$" + formatter.format(money));`

Then go back and look at the output statements that I showed in my first post.

Cheers!

Z
• October 29th, 2012, 12:56 PM
divebomb33
Re: Why so many decimal points in my basic code?
I made the following changes but they still yield this output message
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: class DecimalFormat
location: class Commission
at Commission.main(Commission.java:17)
Java Result: 1

What am I doing wrong?

Here is the whole code I ran-
Code java:

```import java.util.Scanner;     public class Commission{   public static void main (String[] args){ Scanner kb = new Scanner(System.in); double a = 1.1, b, c;   DecimalFormat formattedDollars= new DecimalFormat("\$#,##0.00");           System.out.println("What is your fixed salary?"); b = kb.nextDouble();   c = b * a; System.out.print("With DecimalFormat : Price = " + formattedDollars.format(price)); System.out.println(formatter.format(money)); System.out.println("money = \$" + formatter.format(money)); System.out.println("Your fixed salary is \$" + b +" "); System.out.println("With the current commission being 10% of total sales," + "your total annual compensation is \$" + c);     } }```
• October 29th, 2012, 02:07 PM
Zaphod_b
Re: Why so many decimal points in my basic code?
Quote:

Originally Posted by divebomb33
I made the following changes but they still yield this output message
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: class DecimalFormat

DecimalFormat and (NumberFormat) are in the java.text package, so at the beginning of your program, you can put the following statement to let Java know that's what you are going to use:
Code java:

`import java.text.*;`

...
Quote:

Originally Posted by divebomb33
What am I doing wrong?

Aside from not realizing that you had to import the package containing the class, your code and the reasoning behind it is incomprehensible. I mean I can't comprehend what the heck you expect out of your code:
Code java:

```  // Create a DecimalFormat object named formattedDollars. OK! DecimalFormat formattedDollars= new DecimalFormat("\$#,##0.00"); . . . // Proper use of formattedDollars object but where the heck is "price" defined? // And, why are you printing something labelled "Price" anyhow? Your program // doesn't have anything associated with the price of anything. // System.out.print("With DecimalFormat : Price = " + formattedDollars.format(price)); . . . // Where the heck is "formatter" defined?, Where the heck is "money" defined? System.out.println(formatter.format(money));   // Ditto System.out.println("money = \$" + formatter.format(money));```

Cheers!

Z
• October 29th, 2012, 02:23 PM
divebomb33
Re: Why so many decimal points in my basic code?
Well I imported this-
Code java:

`import java.text.*;`
Code java:

`DecimalFormat formattedDollars= new DecimalFormat("\$#,##0.00");`
You mentioned this to be include-
Code java:

```System.out.print("With DecimalFormat : Price = " + formattedDollars.format(price)); System.out.println(formatter.format(money)); System.out.println("money = \$" + formatter.format(money));```
What do I do with that? I already have this which outputs my results with the excessive decimal points-
Code java:

```System.out.println("Your fixed salary is \$" + b +" "); System.out.println("With the current commission being 10% of total sales," + "your total annual compensation is \$" + c);```
• October 29th, 2012, 03:14 PM
Zaphod_b
Re: Why so many decimal points in my basic code?
I gave several examples. None was intended to be dropped directly into your program, since they used different variable names and various kinds of format that might not be what you are looking for.

My hope was (and is) that you would be able to use the examples to learn ways that you can format currency into a String that can be put into your program with whatever other adornment you see fit to add.

Cheers!

Z
• October 29th, 2012, 05:44 PM
divebomb33
Re: Why so many decimal points in my basic code?
I understand. I believe the mod suggested I do that. What I have so far shows no errors, however the output doesn't show the way I'm looking for-

Code java:

```import java.text.*; import java.util.Scanner;       public class Commission{   public static void main (String[] args){ Scanner kb = new Scanner(System.in); double a = 1.1, b, c;   DecimalFormat formattedDollars= new DecimalFormat("\$#,##0.00");                 System.out.println("What is your fixed salary?"); b = kb.nextDouble();   c = b * a;   System.out.println("Your fixed salary is \$" + b +" "); System.out.println("With the current commission being 10% of total sales," + "your total annual compensation is \$" + c);     } }```
The imports are correct I believe. I think my problem is fixing the System.out.println code that I currently have in there. I'm just not sure what to do. I've reviewed all the previous posts over and over again. I'm really struggling with this.
• October 29th, 2012, 06:22 PM
helloworld922
Re: Why so many decimal points in my basic code?

How to do this:

[code=java]
// your code goes in here
[/code]

This looks like:

Code java:

`// your code goes in here`

You've created your DecimalFormat object, now you need to use it. DecimalFormat has a method called format. This takes a number input and formats it as a String. You can the print this String out as you would any other String.

Code java:

```double value = 3.45123; DecimalFormat currency= new DecimalFormat("\$#,##0.00");   String value_as_string = currency.format(value);   System.out.println("The formatted currency string is: " + value_as_string); System.out.println("The default formatted value is: " + value);```

You don't need to store the result of the format method into a String variable, though. You can just use it directly.

Code java:

```double value = 3.45123; DecimalFormat currency= new DecimalFormat("\$#,##0.00");   System.out.println("The formatted currency string is: " + currency.format(value)); System.out.println("The default formatted value is: " + value);```
• October 29th, 2012, 07:20 PM
Darryl.Burke
Re: Why so many decimal points in my basic code?
This thread has been cross posted here:

Java Programming Forums Cross Posting Rules

• October 29th, 2012, 07:38 PM
divebomb33
Re: Why so many decimal points in my basic code?
I didn't deny getting great advice. I'm just not grasping the subject matter the way I had hoped. I'm looking for what I think is a few lines of code that will make my program work. I just don't know what exactly I'm missing and exactly where to put it in my existing code
Code java:

```import java.text.*; import java.util.Scanner; //program uses scanner     //Class declaration public class Commission{   //main method begins program execution   public static void main (String[] args){ Scanner kb = new Scanner(System.in);   double a = 1.1, b, c; //variables and values     DecimalFormat formattedDollars= new DecimalFormat("\$#,##0.00");     System.out.println("What is your fixed salary?"); //prompts user to enter their fixed salary b = kb.nextDouble();   c = b * a; //this formula will determine an employee's total annual compensation       System.out.println("Your fixed salary is \$" + b +" "); //this will print result onto output screen System.out.println("With the current commission being 10% of total sales," + "your total annual compensation is \$" + c); //this will print programs desired result on output screen to user   }//End method display message }//End class Commission```
• October 29th, 2012, 08:15 PM
jps
Re: Why so many decimal points in my basic code?
Quote:

I just don't know what exactly I'm missing
Code tags?

No one wants to read a bunch of left justified black textual code. There is even a preview button you can use to be sure the whole post looks great before posting.
Show 40 post(s) from this thread on one page
Page 1 of 2 12 Last