Removing Dollar and comma from string

前端 未结 11 1994
天涯浪人
天涯浪人 2020-12-14 10:47

How can we remove dollar sign ($) and all comma(,) from same string? Would it be better to avoid regex?

String liveprice = \"$123,456.78\";
相关标签:
11条回答
  • 2020-12-14 11:28

    In my case, @Prabhakaran's answer did not work, someone can try this.

    String salary = employee.getEmpSalary().replaceAll("[^\\d.]", "");
    Float empSalary = Float.parseFloat(salary);
    
    0 讨论(0)
  • 2020-12-14 11:32
    import java.text.NumberFormat
    
    def currencyAmount = 9876543.21 //Default is BigDecimal
    def currencyFormatter = NumberFormat.getInstance( Locale.US )
    
    assert currencyFormatter.format( currencyAmount ) == "9,876,543.21"
    

    Don't need getCurrencyInstance() if currency is not required.

    0 讨论(0)
  • 2020-12-14 11:40

    Example using Swedish Krona currency

    String x="19.823.567,10 kr";

            x=x.replace(".","");
            x=x.replaceAll("\\s+","");
            x=x.replace(",", ".");
            x=x.replaceAll("[^0-9 , .]", "");
    

    System.out.println(x);

    Will give the output ->19823567.10(which can now be used for any computation)

    0 讨论(0)
  • 2020-12-14 11:41

    Is a replace really what you need?

    public void test() {
      String s = "$123,456.78";
      StringBuilder t = new StringBuilder();
      for ( int i = 0; i < s.length(); i++ ) {
        char ch = s.charAt(i);
        if ( Character.isDigit(ch)) {
          t.append(ch);
        }
      }
    }
    

    This will work for any decorated number.

    0 讨论(0)
  • 2020-12-14 11:43

    Without regex, you can try this:

    String output = "$123,456.78".replace("$", "").replace(",", "");
    
    0 讨论(0)
提交回复
热议问题