How to convert String with comma to Integer and Double

Viewed 236

I am new to Java programming. I am trying to read excel file where the cell data is in String value. I would like to get the value in double or int. Here's the example data: 3,199,800.00 and 400,573.80. Now, I want to get the value as 3199800 and 400573.8.

I can get those values using this code:

String value = valueCell.getStringCellValue()
    .trim()
    .replace(",", "")
    .replace(".00", "")
    .replace(".10", ".1")
    .replace(".20", ".2")
    .replace(".30", ".3")
    .replace(".40", ".4")
    .replace(".50", ".5")
    .replace(".60", ".6")
    .replace(".70", ".7")
    .replace(".80", ".8")
    .replace(".90", ".9");

Is there a way where I can minimize the above code. Thank you!

Edited: Just to add, I want to keep the result as a string. thank you!

4 Answers

Well you have to remove the commas in your case so the easiest way I could thing of is this one

String someExcelNumber = "3,199,800.00";
System.out.print(Double.parseDouble(someExcelNumber.replace(",","")));

First you remove the commas then you parse them to double or any other format up to you, but if the commas wasn't removed a NumberFormatException will be thrown

There's no need to trim off excess zeros, you can simply parse them straight into numbers with Double.parseDouble or Integer.parseInt (after stripping the commas). So for example:

Double.parseDouble(number.replace(",", ""))

If you wanted to keep it as a string, you could use the following regex:

number.replace(",", "").replaceFirst("(\\d+)\\.0+$|(\\d+\\.[1-9]+)0*$", "$1$2")

Which replaces any zeroes that a preceded by a . and any number of digits.

Possible using only parseDouble:

static String st1 = "3,199,800.00";
static String st2 = "400,573.80";

public static void main(String[] args) {

    System.out.println(Double.parseDouble(st2.replaceAll(",", "")));

    System.out.println((int)Double.parseDouble(st1.replaceAll(",", "")));

}

results:

400573.8

3199800

Try this.

static String convert(String input) {
    return input.replaceAll(",|\\.00$|(?<=\\..)0$", "");
}

public static void main(String[] args) {
    System.out.println(convert("3,199,800.00"));
    System.out.println(convert("400,573.80"));
}

output:

3199800
400573.8
Related