How to convert a string to a number

C

chirs

Hi,

How to convert a string such as "1,000" to a number? I tried
Integer.parseInt("1,000");. But it did not work.

Thank you.

Chris
 
D

Dave Miller

Hi,

How to convert a string such as "1,000" to a number? I tried
Integer.parseInt("1,000");. But it did not work.

Thank you.

Chris
Look at java.text.NumberFormat - it can handle extraneous input like
commas, monetary symbols, etc.
 
S

Sudsy

chirs said:
Hi,

How to convert a string such as "1,000" to a number? I tried
Integer.parseInt("1,000");. But it did not work.

Thank you.

Chris

Not surprising that it didn't work. Commas as part of the number don't
generally reflect how computers deal with numbers. But there is a class
designed to handle these situations. Try this:

import java.text.DecimalFormat;
....
DecimalFormat formatter = new DecimalFormat( "#,##0" );
String s = "1,000";
int i = -1;
try {
i = formatter.parse( s ).intValue();
}
catch( ParseException e ) {
...
}

Don't you just love the javadocs?
 
R

Roedy Green

How to convert a string such as "1,000" to a number? I tried
Integer.parseInt("1,000");. But it did not work.

It does not like the comma. You will have to filter it out before
hand.
 
S

Sudsy

Roedy asks:
When you do that, what sorts of string are acceptable. Does it insist
on the comma?

It's actually very forgiving. It seems to completely ignore
the commas, the number of digits between them, etc. I wrote
this quick test:

public class NumberTest {
public static void main( String args[] ) {
DecimalFormat formatter = new DecimalFormat( "#,##0" );
int parsed;
String formatted;
for( int i = 0; i < args.length; i++ ) {
try {
parsed = formatter.parse( args
).intValue();
formatted = formatter.format( parsed );
System.out.println( "Original = " +
args +
", parsed = " + parsed +
", formatted = " + formatted );
}
catch( Exception e ) {
System.err.println( e.toString() );
}
}
}
}

Here's a test run:

$ java NumberTest 1,000 1000 4,1567,890 4567890 1,34546
Original = 1,000, parsed = 1000, formatted = 1,000
Original = 1000, parsed = 1000, formatted = 1,000
Original = 4,1567,890, parsed = 41567890, formatted = 41,567,890
Original = 4567890, parsed = 4567890, formatted = 4,567,890
Original = 1,34546, parsed = 134546, formatted = 134,546
$

So it's more powerful on the formatting end than the parsing one.
Fair enough!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top