ahamel77
asked on
parseDouble parameters
I'm using parseDouble to convert String amounts to a double format. My string has commas as decimal separators (i.e 1,000,000.00) parseDouble throws an error when trying to convert the numbers with commas. Is there a way to tell parseDouble to ignore the commas or do I have to remove the commas from my string prior to sending it to parseDouble?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You have to import the java.text.*; package for the above to work.
The sites below are the best that can be found for explaining every class in the Java language.
http://java.sun.com/j2se/1.3/docs/api/index.html SDK 1.3 documentation
http://java.sun.com/j2se/1.4/docs/api/index.html SDK 1.4 documentation
http://java.sun.com/j2se/1.3/docs/api/index.html SDK 1.3 documentation
http://java.sun.com/j2se/1.4/docs/api/index.html SDK 1.4 documentation
If removing the commas is OK with you, then do this:
// assuming 'str' is the string that contains the string-form of the double number
// Use a temporary StringBuffer object for removing the commas
StringBuffer sb = new StringBuffer ( str ) ;
for ( int i = 0 ; i < sb.length () ; i ++ )
if ( sb.charAt ( i ) == ',' )
{
sb.deleteCharAt ( i ) ;
i -- ; // not needed as there won't be successive commas, but no harm in putting this statement
} // end if, for
double doubleVal = Double.parseDouble ( sb.toString () ) ;
This will remove all commas from the StringBuffer object and then pass its string-equivalent to parseDouble (). This way, 'str' will retain its original value (including commas). If you want it to hold the new value, then you can do:
str = sb.toString () ;
double doubleVal = Double.parseDouble ( str ) ;
Hope that helps!
Mayank.
// assuming 'str' is the string that contains the string-form of the double number
// Use a temporary StringBuffer object for removing the commas
StringBuffer sb = new StringBuffer ( str ) ;
for ( int i = 0 ; i < sb.length () ; i ++ )
if ( sb.charAt ( i ) == ',' )
{
sb.deleteCharAt ( i ) ;
i -- ; // not needed as there won't be successive commas, but no harm in putting this statement
} // end if, for
double doubleVal = Double.parseDouble ( sb.toString () ) ;
This will remove all commas from the StringBuffer object and then pass its string-equivalent to parseDouble (). This way, 'str' will retain its original value (including commas). If you want it to hold the new value, then you can do:
str = sb.toString () ;
double doubleVal = Double.parseDouble ( str ) ;
Hope that helps!
Mayank.