user2207495
user2207495

Reputation: 325

Parse String to Integer/Long/Float/Double

I'm trying to properly parse string representation of number. Parser provides me with numeric value Integer/Long/Float/Double however when i try to parse with NumberFormat like :

String number = "1.0";
NumberFormat.getNumberInstance().parser(number);

It returns a Long type. However when i try to parse "1.1" it properly deduce Double (Why not float?). Should i write my own number parser or there is a possibility to tweak it the way that it will properly deduce types. Integers as Integers (not Long). Float as Float (not Double). Long as Long and Double as Double.

Upvotes: 0

Views: 2176

Answers (1)

SamHoque
SamHoque

Reputation: 3154

Why not use java's built in number parsers?

Double.parseDouble() Float.parseFloat() Integer.parseInt()

and so on...

edit:

After looking at your comment you can try using this

    String number = "1.0";
    if (isInteger(number)) {
        //parse Int
    } else if (isDouble(number)){
        //parse Double
    }

and the methods:

public static boolean isInteger(String s) {
    try {
        Integer.parseInt(s);
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

public static boolean isDouble(String s) {
    try {
        Double.parseDouble(s);
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

public static boolean isFloat(String s) {
    try {
        Float.parseFloat(s);
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

Upvotes: 1

Related Questions