• Post Reply Bookmark Topic Watch Topic
  • New Topic

Coverting formatted string to numeric  RSS feed

 
M Burke
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an input where the numbers are formatted and they need to be convert to integers or doubles. I know Java has the NumberFormat class, but I need to do the opposite.

Examples:
"200,000" to numeric 200000
"23%" to numeric 23
"1,000.44" to numeric 1000.44
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66306
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you thoroughly analyzed the features of the NumberFormat class?
 
Les Morgan
Rancher
Posts: 779
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Double and Integer has a valueOf method, I think that may be what you are seeking.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
M Burke wrote:I have an input where the numbers are formatted and they need to be convert to integers or doubles.

I doubt there's a single solution to all your examples - especially the second one, which looks unusual to me. Many programs (eg, Excel) would convert that to 0.23.

Winston
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Double/Integer valueOf method is one way, the other is the parseXXX method.

The major differences between the valueOf and parseXXX methods are:
the parseXXX a) throws a NumberFormatException when the input is malformed (eg not a number) and b) return the primitive type (int, double, long etc)
the valueOf returns an object/class or the auto-boxed type (Integer, Double, Long etc)
 
M Burke
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what I ended up doing. It works, but there is probably a better way.

 
chrstian ferma
Ranch Hand
Posts: 72
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why not string .replace before parsing replace "," to "" and also replace "%" to "" then parse to type that you need double or int
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!