简体   繁体   中英

Number with group-separator and decimal-separator convert into decimal number

I want to convert the number "4,471.26" into decimal number "4471.26" .

Actually number " 4,471.26 " is received as String and for further process, need to convert it into Decimal number.

"4,471.26" - is just a format,so value is keeps changing every-time. This value could be anything like " 654,654,25.54"

Tried by considering comma (,) as group -separator. But looks like has different ASCII values.

String Tempholder = "4,471.26";
Decimal.valueOf(Tempholder.replaceAll(getGroupSeparator(), ""));



  private char getGroupSeparator() {
            DecimalFormat decFormat = new DecimalFormat();
            DecimalFormatSymbols decSymbols = decFormat.getDecimalFormatSymbols();
            return Character.valueOf(decSymbols.getGroupingSeparator());
        }

Below code would be temporary solution, but it will not work other geo regions.

String Tempholder = "4,471.26";
Decimal.valueOf(Tempholder.replaceAll(",", ""));

Kindly help ..

you can do it like this :

public class JavaCodes{
public static void main(String[] args) {
    String str = new String("4,233.19");
    str = str.replaceFirst(",", "");
    System.out.println(Double.valueOf(str));
  }
}

Ok, some assumptions first

  • You don't know the locale beforehand
  • If just one separator is found, and it appears only once, we treat it as a decimal separator (for simplicity)
  • If just one separator is found but it appears multiple times, it's a thousands separator
  • Any non-digit character is a valid separator
  • If there are more than two non-digit characters in a string, that's an error.

So here's the algorithm

  • Find the first non-digit character and temporarily consider it a decimal separator
  • If another non-digit character is found
    • If it's the same as the decimal separator, and we still don't have a thousands seprator, make that the thousands separator and reset the decimal separator
    • If it's the same as the decimal separator, and we already have a thousands separator, that's an error
    • If it's not the same as the decimal separator, it's the thousands separator
  • Remove from the original string all occurrences of the thousands separator (if present)
  • Substitute the decimal separator with a dot
  • Parse as double.

And here is the code.

public class Test {

    public static double parseNumber(String x) {
        Character thousandsSeparator = null;
        Character decimalSeparator = null;

        for (int i = 0; i < x.length(); i++) {
            if (!Character.isDigit(x.charAt(i))) {
                if (decimalSeparator == null) {
                    decimalSeparator = x.charAt(i);
                } else {
                    if (decimalSeparator.equals(x.charAt(i))) {
                        if (thousandsSeparator == null) {
                            thousandsSeparator = x.charAt(i);
                            decimalSeparator = null;
                        } else {
                            if (!thousandsSeparator.equals(x.charAt(i))) {
                                throw new IllegalArgumentException();
                            }
                        }
                    } else {
                        thousandsSeparator = x.charAt(i);
                    }
                }
            }
        }

        // remove thousands separator
        if (thousandsSeparator != null) {
            int formerSeparatorPosition;
            while ((formerSeparatorPosition = x.indexOf(thousandsSeparator)) != -1) {
                x = x.substring(0, formerSeparatorPosition) + x.substring(formerSeparatorPosition + 1);
            }
        }

        // replace decimal separator with a dot
        if (decimalSeparator != null) {
            x = x.replace(decimalSeparator, '.');
        }
        return Double.parseDouble(x);

    }

    public static void main(String args[]) {
        System.out.println(parseNumber("123.45"));
        System.out.println(parseNumber("123,45"));
        System.out.println(parseNumber("1.234,5"));
        System.out.println(parseNumber("1,234.5"));
        System.out.println(parseNumber("1,234,567.512"));
        System.out.println(parseNumber("1.234.567,512"));
        ystem.out.println(parseNumber("1.234.567"));
        System.out.println(parseNumber("1_234_567|34")); // works with any two characters, if there are just two
        try {
            System.out.println(parseNumber("1_234_567|34,7")); // invalid
        } catch (IllegalArgumentException e) {
            System.out.println("Too many separators!");
        }
    }
}

It is quite circumstantial to parse to a BigDecimal . To a double it is easier but floating point is just an approximation, and will loose the number's precision. 0.2 == 0.20 == 0.200 == (actually something like) 0.1999999987.

    String text = "4,471.26";
    DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
    format.setParseBigDecimal(true);
    BigDecimal number = (BigDecimal) format.parseObject(text);
    // number.scale() == 2

The US locale uses your desired separators.

Thank you guys, for all your suggestion and helps. I figure out the below solution. Convert it into decimal number, And applicable to all geo region.

public static void geoSp() {
    String a = "4.233,19";
    NumberFormat as = NumberFormat.getInstance();
    double myNumber = 0;
    try {
        myNumber = as.parse(a).doubleValue();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(String.valueOf(myNumber));
}

   gives  Out put :- 4233.19

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM