Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy convert String "1,503" to Integer

Tags:

groovy

I'm parsing a file that has integer values using commas to separate thousands.

String s = "1,503"
Integer i = new Integer(s)

does not work, throws a parse exception. Is there an easy way to parse this?

Thanks

like image 911
Ray Avatar asked Oct 23 '11 14:10

Ray


2 Answers

A slightly more groovy method might be;

int a = java.text.NumberFormat.instance.parse( '1,234' )

But this will use the default locale

like image 131
tim_yates Avatar answered Sep 20 '22 22:09

tim_yates


Use NumberFormat instead. For example, in Java:

import java.util.*;
import java.text.*;

public class Test {
    public static void main(String args[]) throws ParseException {
        NumberFormat format = NumberFormat.getIntegerInstance(Locale.US);
        Long parsed = (Long) format.parse("1,234");
        System.out.println(parsed);
    }
}

(You can then get the integer value from the Long, of course.)

I've explicitly specified Locale.US to guarantee that comma is used as the thousands separator; you may want to use a different locale if the input can vary.

like image 35
Jon Skeet Avatar answered Sep 19 '22 22:09

Jon Skeet