如果字符串实际上是数字,则将百分比符号(%)附加到字符串

我是Java的新手,正在学习核心概念,遇到了一个问题,例如,我需要在字符串数字后附加%符号。

String st = "0.9" -> "0.9%"
String st2 = "1.5" -> "1.5%"
String st1 = "AAA09" -> Should throw an exception.

我在下面尝试过,但没有运气,将不胜感激。

public static String convertToCurrancy(String value) {
        Pattern p = Pattern.compile("\\d+(\\.\\d+)%");
        String bigDecimalConvertedValue = null;
        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        DecimalFormat decimalFormat = new DecimalFormat(p.toString(), symbols);

        try {
            BigDecimal bigDecimal = new BigDecimal(value);
            bigDecimalConvertedValue = decimalFormat.format(bigDecimal);
            return bigDecimalConvertedValue;
        } catch (Exception e) {
            return value;
        }

    }
评论
  • 深蓝Xx
    深蓝Xx 回复

    Instead of throwing exceptions, you may add % to numbers only, and keep the rest of strings unchanged using a mere

    String result = text.replaceFirst("^\\d+(?:\\.\\d+)?$", "$0%");
    

    See the regex demo.

    细节

    • ^ - start of string
    • \d+ - 1+ digits
    • (?:\.\d+)? - an optional non-capturing group matching 1 or 0 occurrences of
      • \. - a dot
      • \d+ - 1+ digits
    • $ - end of string.

    Inside the replacement pattern, the $0 placeholder is used to refer to the whole match value.