Results 1 to 3 of 3

Thread: Parsing dollar amounts from a string & totalling

  1. #1

    Thread Starter
    Hyperactive Member rockies1's Avatar
    Join Date
    Jul 1999
    Location
    Stuck at work
    Posts
    375

    Parsing dollar amounts from a string & totalling

    I have a file that has dollar amounts in it in each line of the file.

    I need to pull the amount out and total them. Amounts will always have 0, 1, or 2 decimals.

    I used doubles, but I end up getting odd totals like this: 17362.899999999998

    This occurs even when adding numbers like 569.91 and 419.03. I get 988.9399999999999.

    How can I make sure I get the actual amount and not something funky?

    Thanks!
    Morgan
    [email protected] - Home
    [email protected] - Work
    Using VB6 SP6 but trying to learn VB2005EE

  2. #2
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    posted by rockies1

    This occurs even when adding numbers like 569.91 and 419.03. I get 988.9399999999999.

    How can I make sure I get the actual amount and not something funky?
    Code:
     import java.util.Locale; 
     import java.text.NumberFormat;
    
     public class W{
      public static void main(String[] args){
     
      double x = 569.91 + 419.03; 
      System.out.println(x); 
       
        NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); 
        System.out.println(nf.format(x)); 
    
        NumberFormat nf2 = NumberFormat.getCurrencyInstance(Locale.JAPAN); 
        System.out.println(nf2.format(x)); 
    
        NumberFormat nf3 = NumberFormat.getCurrencyInstance(Locale.GERMANY);    
        System.out.println(nf3.format(x)); 
      }
    }

  3. #3
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    If you want to parse the values out from Strings.....
    Code:
     import java.util.Locale; 
     import java.text.NumberFormat;
    
     public class W{
      public static void main(String[] args){
     
      String s1 = "569.91"; 
      String s2 = "419.03"; 
      double d1 = Double.parseDouble(s1); 
      double d2 = Double.parseDouble(s2); 
      double x = d1 + d2;
      System.out.println(x);     
    
       try{
       
        NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); 
        System.out.println(nf.format(x)); 
    
        NumberFormat nf2 = NumberFormat.getCurrencyInstance(Locale.JAPAN); 
        System.out.println(nf2.format(x)); 
    
        NumberFormat nf3 = NumberFormat.getCurrencyInstance(Locale.GERMANY);    
        System.out.println(nf3.format(x));
       
       }catch(NumberFormatException e){System.err.println(e);} 
      }
     }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width