简体   繁体   中英

JAVA How do i apply digit grouping to a equation

I am trying to digit group an equation inputted by the user with indeterminate in size for example; 9000 + 1000 x 2 this is stored in a string and I want to turn it into 9,000 + 1,000 x 2. The code I have at the moment will only work until it reaches a non-number is there I way I can record the location of where it found the non-number and skip over it to get to the next number.

My code so far;

DecimalFormat formatter = new DecimalFormat("#,###.##");

    if(loop == true) {
        double amount = ((Number)NumberFormat.getInstance().parse(CalculatorComponent.values)).intValue();  
        temp = formatter.format(amount);
        System.out.println(temp);
    }

the loop variable is always set to true at present, and CalculatorComponent.values is a string of the currently inputted data, this includes the operators.

Here's a solution parsing your input with regular expressions and replacing the values.

// your format
DecimalFormat formatter = new DecimalFormat("#,###.##");
// your input
String input = "9000 + 1000 x 2";
// StringBuffer holding the replaced String
StringBuffer result = new StringBuffer(input.length());
// pattern for 1+ consecutive digits
Pattern pattern = Pattern.compile("\\d+");
// matcher for your input
Matcher matcher = pattern.matcher(input);
// iterating over matches
while (matcher.find()) {
    // replacing matches
    matcher.appendReplacement(
        result, 
        formatter.format(Integer.valueOf(matcher.group()))
    );
}
// appending tail (not applicable in this example, but need to have)
matcher.appendTail(result);
// printing result
System.out.println(result);

Output

9,000 + 1,000 x 2

Notes

  • Matcher#appendReplacement takes a StringBuffer , not a StringBuilder - never figured out why, afaik it doesn't leverage any multi-threaded operations
  • You need to convert the digit matches to Number in order to format them (hence the Integer.valueOf invocation), but that operation is safe in this context
  • The Matcher#appendTail invocation is useful if you have any non-matching text after the last token, so it can be added to the result too
  • This will work for plain digit integer numbers. However, if you have already localized number expressions in your equation, or decimal numbers , you're probably going to need a fine-tuned pattern

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