Joakim
Joakim

Reputation: 3294

How do I parse ANY Number type from a String in Java?

How do I parse ANY Number type from a String in Java?

I'm aware of the methods like Integer.parseInt(myString) and Double.parseDouble(myString) but what I optimally want is a method like Number.parseNumber(myString) which doesn't exist. How can I achieve that behaviour in another way? (I want the parsed Number to reflect the String "exactly" in terms of for example number of decimals).

Example:

"0" => Number (internally of Integer subclass)

"0.0" => Number (internally of Double subclass)

Also, no ugliness like checking for decimal separators etc.

Upvotes: 5

Views: 7128

Answers (3)

Zé Henriques
Zé Henriques

Reputation: 323

Better way is to use BigDecimal class.

BigDecimal n = new BigDecimal("1.0");

Methods for needed values

n.byteValue();  
n.intValue();  
n.shortValue();  
n.longValue();  
n.floatValue();  
n.doubleValue();

Upvotes: 2

Joakim
Joakim

Reputation: 3294

Number number = NumberFormat.getInstance().parse(myString);

Seems to do the trick...

Upvotes: 8

OldCurmudgeon
OldCurmudgeon

Reputation: 65889

You are probably looking for BigDecimal.

Please remember that a number can be represented in many forms as a string. e.g. 1 is the same number as 1.0000000.

Upvotes: 1

Related Questions