Results 1 to 5 of 5
Thread: Converting data types
- 01-11-2008, 09:06 PM #1
Member
- Join Date
- Jun 2007
- Posts
- 14
- Rep Power
- 0
Converting data types
I'm trying to convert string representations of numbers that contain commas into integers.
For example, converting
80,000
125,000
8,000,000,000
from their string representation into an int data type.
I have an ugly brute force way of doing it by breaking up the "string" into individual characters, delete the commas and concantenate it all back together and then convert to int. It's ugly - anyone know of a better way, preferably a native method in java that will perform the conversion?
Thanks a bunch!
- 01-11-2008, 09:55 PM #2
Hey, i usually don't like handing out code, but i enjoyed doing this one.
If you are unfamiliar with arrays and ArrayLists and loops, then you should learn about them. You will be using them ALOT in programming.Java Code:import java.util.ArrayList; public class Comma { public static void main(String[] args) { String num = "5,000,000"; char[] chars = num.toCharArray(); ArrayList<Character> charList = new ArrayList<Character>(); for(int i = 0; i < chars.length; i++) { if((chars[i] + "").equals(",")) continue; else charList.add(chars[i]); } for(char e : charList) { System.out.print(e); } } }
- 01-11-2008, 10:46 PM #3
Member
- Join Date
- Jan 2008
- Posts
- 24
- Rep Power
- 0
there is an easier way of doing that.
long number = Long.parseLong(str.replaceAll(",",""));
- 01-11-2008, 10:53 PM #4
Member
- Join Date
- Jan 2008
- Posts
- 24
- Rep Power
- 0
- 01-12-2008, 12:48 AM #5
Similar Threads
-
Primitive data types of Java
By Java Tip in forum Java TipReplies: 0Last Post: 03-28-2008, 07:29 PM -
Displaying different image types
By splinter64uk in forum AWT / SwingReplies: 1Last Post: 12-05-2007, 08:12 AM -
Comparing types, integer with null
By Felissa in forum New To JavaReplies: 1Last Post: 07-05-2007, 06:32 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks