Hello

I have this:

String price="10,00 €";
int num=2;
int sum=Integer.valueOf(price)*num;
System.out.println(sum); //Should print out AT LEAST 20,00

But note: That € sign can be $, €, £ or another AND it can come before or after the numeric float amount.

What is the best way to do this?

Thank you

Recommended Answers

All 56 Replies

import java.util.*;

class DW001{
    public static void main(String args[]){
        String mon = "€ 10,00";
        String exploder= "$€£";   //Add any other currency symbols,chars here.They have to be of the proper encoding
        StringTokenizer gen = new StringTokenizer(mon,exploder);
        System.out.println(gen.nextToken().trim());
    }
}

And regarding the comma,it would be better if it were a decimal.Then you can easily typecast it.Else there are certain methods as to normalizing them like bringing down 1,000,000 to 1000000

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

Java 7 API doc for StringTokenizer

there are see two issues

  1. decimal separator is dot programming languages

  2. use Numbers instance with Currency formatter, then output to the Java GUI will be 10,00, but stored with dot internally

Some currencies use dots, others use commas. This is not something up to me.

Regarding the

String exploder= "$€£"; //Add any other currency symbols,chars here.They have to be of the proper encoding
StringTokenizer gen = new StringTokenizer(mon,exploder);

code; You do realize that I would have to add all the currencies known, right?

Also, that code does not take in count if the symbol is before or after to again put it before or after the calculation...

Any ideas?

I'm not clear on your requirement. Is it like this...?

You have a String containing a formatted number. The formatting may include (arbitrary?) thousands delimiters, (arbitrary?) decimal delimiter, (arbitrary?) pre- or post-fix currency symbol.
You need to extract the numerical value to use in arithmetical calculations.
You then need to convert the result back toa formatted String using the same formatting as the original String.
Some/any of the formatting items (delimieters, symbols) can/cannot be pre-defined

I'm not clear on your requirement. Is it like this...? You have a String containing a formatted number. The formatting may include (arbitrary?) thousands delimiters, (arbitrary?) decimal delimiter, (arbitrary?) pre- or post-fix currency symbol.
You need to extract the numerical value to use in arithmetical calculations.
You then need to convert the result back toa formatted String using the same formatting as the original String.
Some/any of the formatting items (delimieters, symbols) can/cannot be pre-defined

My string as plain english is

"nine hundred ninety nine dollars with ninety nine cents"

So it would contain:

"$999.99"

and it can also be

"nine hundred ninety nine euros with ninety nine cents"

Which would contain:

"999,99 €"

I need to be able to treat BOTH of those numbers and do operations on them and give me resutls and then once again put the symbol in the correct position after/before.

We will never reach a thousand (hell, its going to be difficult to even reach a hundred) so additional decimals is a nonissue.

So
no thousands delimiters
decimal delimiter is always . (never ,)
curreency symbol is one of $€
$ is always prefixed, € is always postfixed
?
or are there more possibilities?

So
no thousands delimiters
decimal delimiter is always . (never ,)
curreency symbol is one of $€
$ is always prefixed, € is always postfixed
?
or are there more possibilities?

???

I gave you two examples:

$999.99

999,99 €

And clearly stated they are both decimal based so the decimal delimiter can be "." "," or others...
Currency symbol can be any currency symbol known; I see over 50 on Wikipedia!
AFAIK, in dollars the $ is always prefixed and in euros the € is always postfixed but again, can change.

OK, my eyesight isn't what it was, the , and . look the same on my screen!

How about some thing like this?

Parse the input to get a complete format defined by <decimal separator> <currency symbol> < currency prefix or postfix>... it's not difficult. ie:

  • have a list of known decimal separators. Search the input to see which it is, remember that
  • have a list of known currency symbols. Search the input to see which it is, remember that
  • check whether the currency symbol is before or after the number, remember that
  • (extract the digits before & after the decimal to get the numeric value).

You now have a complete format definition, so it will be easy to format any results using those 3 items.

OK, my eyesight isn't what it was, the , and . look the same on my screen!

I agree. They are difficult to tell apart on PC.

Parse the input to get a complete format defined by <decimal separator> <currency symbol> < currency prefix or postfix>... it's not difficult. ie: have a list of known decimal separators. Search the input to see which it is, remember that have a list of known currency symbols. Search the input to see which it is, remember that check whether the currency symbol is before or after the number, remember that (extract the digits before & after the decimal to get the numeric value). You now have a complete format definition, so it will be easy to format any results using those 3 items.

Not sure how to parse that individually and then group them together in the correct order/fashion. Id know how to seperate with ONE character but not different ones in different positions.

Just break it down into smaller and smaller steps, eg stuff like...

parse:
   for each symbol in currency symbols
      if (source.indexOf(symbol) >= 0) this is the right symbol...
   ...
   if (source.indexOf(symbol)  < source.indexOf(decimalSeparator)) currency is prefix
   else  currency is postfix

format:
   result = (numeric value converted to simple syring)
   if (currency is prefix) result = symbol + " " + result
   else result = result + " " + symbol

So I would have a array called symbols with chars with all the currency symboles possible (huge array but oh well)

Example:

char[] symbols = new char[] { '€','$' };
        char symbol=' ';
        for (int i=0;i<symbols.length;i++)
        {
            symbol=symbols[i];
        }

But after that I kinda got lost.

(Lost at "decimalSeparator" and "source")

I was just using "source" as the name of the input string that you are trying to parse. And decimalSeparator for the . or , or whatever, exactly like the currency symbol.

String price="16,00 €";
        char[] symbols = new char[] { '€','$' };
        char symbol=' ';
        for (int i=0;i<symbols.length;i++)
        {
            symbol=symbols[i];
             if (price.indexOf(symbol) >= 0) //this is the right symbol...
             {

             }
        }

So now what: I have to make another char array for decimalseperator???

You mught want to finish that bit first (exit the loop) then yes, you can do the decimal separator in exactly the same way.
(ps got other stuff on my plate right now, won't be able to respond so fast for while)

You mught want to finish that bit first (exit the loop) then yes, you can do the decimal separator in exactly the same way.
(ps got other stuff on my plate right now, won't be able to respond so fast for while)

Basically you are asking me to do a double for loop, typical in two dimensional arrays...

No, its two independent loops, one after the other. 2D arrays lead to nested loops (one inside the other).
Please don't think in terms of me asking you to do things. I'm not running thei project, I'm just making some suggestions and hints. Take whatever you thnk is useful and add it to your own ideas.

Stop coding for a minute and think through the whole pseudo-code. Write your own complete pseudo code so you have the structure clear in your own head before getting into the details of the Java.

String price="16,00 €";
        int position;
        char[] symbols = new char[] { '€','$' };
        char[] decimalseperators= new char[] { '.',',' };
        char symbol=' ';
        char deci=' ';
        boolean pre;
        for (int i=0;i<symbols.length;i++)
        {
            symbol=symbols[i];
             if (price.indexOf(symbol) >= 0) //this is the right symbol...
             {
                 position=price.indexOf(symbol);
                 break;
             }
        }
        for (int i=0;i<decimalseperators.length;i++)
        {
            deci=decimalseperators[i];
            if (price.indexOf(position)  < price.indexOf(deci))
            {
                pre=true;
            }
            else
            {
                pre=false;
            }
        }

This looks pretty good and logic.

pre is a variable if its prefixed (true) or postfixed (false)

You forgot to do the indexOf test for decimal separator to find which separator is actually present in the price (it should be just like the code for currency symbol). Then whe you have finished with that loop you will know both the currency symbol and the decimal separator, so then (and only then) you can then do the test to see whether the currency comes before or after the decimal.

Also line 13 you get the position of the currency symbol, so you don't need to do that again on line 20. Either way indexOf(position) has to be a mistake.

String price="16,00 €";
        int positions;
        int positiond;
        char[] symbols = new char[] { '€','$' };
        char[] decimalseperators= new char[] { '.',',' };
        char symbol=' ';
        char deci=' ';
        boolean pre;
        for (int i=0;i<symbols.length;i++)
        {
            symbol=symbols[i];
             if (price.indexOf(symbol) >= 0) 
             {
                 positions=price.indexOf(symbol);
                 break;
             }
        }
        for (int i=0;i<decimalseperators.length;i++)
        {
            deci=decimalseperators[i];
            if (price.indexOf(deci)  >=0)
            {
                positiond=price.indexOf(deci);
                break;
            }

        }

        if (positions >positiond)
         {
             pre=false;

         }
        else
        {
            pre=true;
        }

This should work.

Looks OK so far - time to run some tests.

String price="16,00 €"; //Price
        int multiply=2; //Multiplcation that I want to do to price
        int positions=0; //Position of the symbol
        int positiond=0; //Position of the decimal
        char[] symbols = new char[] { '€','$' }; //Symbols that are avaliable
        char[] decimalseperators= new char[] { '.',',' }; // Decimal markers that are avaliable
        char symbol=' '; //Somewhere to store the symbol
        char deci=' '; //Somewhere to store the decimal
        boolean pre; //Check if the decimal is before or after the the symbol

        for (int i=0;i<symbols.length;i++) //I run thru the entire symbol array and the price itself to look for the symbol
        {
            symbol=symbols[i];
             if (price.indexOf(symbol) >= 0) 
             {
                 positions=price.indexOf(symbol); //I store the position of the symbol
                 break;
             }
        }
        for (int i=0;i<decimalseperators.length;i++) //I run thru the entire decimal array and the price itself to look for the decimal
        {
            deci=decimalseperators[i];
            if (price.indexOf(deci)  >=0)
            {
                if (deci!='.') //If the decimal is not a dot, for compatibility reasons, I change it to a dot
                {
                    StringBuilder newprice = new StringBuilder(price);
                    newprice.setCharAt(price.indexOf(deci), '.');
                    price=newprice.toString();
                }
                positiond=price.indexOf(deci); //I store the position of the decimal point
                break;
            }

        }

        if (positions >positiond) //If symbol after the decimal
         {
             pre=false;

         }
        else //If the symbol is before the decimal
        {
            pre=true;
        }
        float result=Float.parseFloat(price)*Float.parseFloat(String.valueOf(multiply)); //I store it as a float for decimal reasons

        if (pre==false) //Put it all together again
        {
            price=result+" "+symbol;
        }
        else
        {
            price=symbol+" "+result;
        }

        System.out.println(price); //Print it out
        System.exit(1);

Here it is. Gives me a error on the result line with your standard

Exception in thread "main" java.lang.NumberFormatException: For input string: "16.00 €"
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at java.lang.Float.parseFloat(Unknown Source)
    at tests.Tests.main(Tests.java:79)

I have to remove the symbol.......

parseFloat should do it but....

Why do you think parseFloat will remove unwanted symbols? Did you check the API doc? The only thing it ignores is leading/trailing white space.
Because your currency symbol ould be anything you will have to remove it yourself.
Because your decimal separator could be anything you will have to parse the two parts of the number separately, or replace your separator with a standard . before passing it to parseFloat

Because your currency symbol ould be anything you will have to remove it yourself.

How can I remove everything except numbers? (Yes, I know Ill have to switch the orders of the fors)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.