【问题标题】:Format currency without currency symbol格式化没有货币符号的货币
【发布时间】:2012-01-29 07:14:13
【问题描述】:

我正在使用NumberFormat.getCurrencyInstance(myLocale) 为我给定的语言环境获取自定义货币格式。但是,这总是包含我不想要的货币符号,我只想要给定语言环境的正确货币数字格式,而没有货币符号。

执行format.setCurrencySymbol(null) 会引发异常..

【问题讨论】:

  • 你试过.setCurrencySymbol("")吗?
  • 当不需要货币时,为什么不使用NumberFormat#getInstance( Locale )
  • @home,结果不一样。示例:使用 NumberFormat.getInstance() 时,结果可能为“1,200”,但使用 NumberFormat.getCurrencyInstance() 时,结果为“1,200.00”
  • 例如,瑞士法郎docs.microsoft.com/en-us/globalization/locale/… 大多数货币使用与区域设置中的数字相同的小数和千位分隔符,但这并不总是正确的。在瑞士的某些地方,他们使用句点作为瑞士法郎的小数分隔符 (Sfr. 127.54),但在其他地方使用逗号作为小数分隔符 (127,54)

标签: java currency number-formatting


【解决方案1】:

以下作品。有点难看,但是很符合约定:

NumberFormat nf = NumberFormat.getCurrencyInstance();
DecimalFormatSymbols decimalFormatSymbols = ((DecimalFormat) nf).getDecimalFormatSymbols();
decimalFormatSymbols.setCurrencySymbol("");
((DecimalFormat) nf).setDecimalFormatSymbols(decimalFormatSymbols);
System.out.println(nf.format(12345.124).trim());

您还可以从货币格式中获取模式,删除货币符号,并从新模式中重建新格式:

NumberFormat nf = NumberFormat.getCurrencyInstance();
String pattern = ((DecimalFormat) nf).toPattern();
String newPattern = pattern.replace("\u00A4", "").trim();
NumberFormat newFormat = new DecimalFormat(newPattern);
System.out.println(newFormat.format(12345.124));

【讨论】:

  • 在您使用负数之前,它会再次显示符号。我确定这一定是一个错误。
  • 要修复显示货币的负数,您可以添加以下行:((DecimalFormat) nf).setNegativePrefix(""+decimalFormatSymbols.getMinusSign());
  • pattern.replace("\u00A4", "").trim()
  • 好答案@JB
【解决方案2】:

改为用空字符串设置:

DecimalFormat formatter = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.US);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setCurrencySymbol(""); // Don't use null.
formatter.setDecimalFormatSymbols(symbols);
System.out.println(formatter.format(12.3456)); // 12.35

【讨论】:

  • 这同样是正确的,虽然只能选择一个答案作为正确的答案..
  • 我认为重点是 Robin 写的:不需要getCurrencyInstance,只需使用getNumberInstance
  • 我认为您可能还需要在第二个示例中设置 formatter.setMinimumFractionDigits(2);
  • @JoshDM:你不应该在这里硬编码“2”,除非你知道你总是想要美元,因为货币的小数点数量不同。
  • @JoachimSauer 我当然可以在 5 年前的评论中硬编码它;我将其留给原始请求者来设计一种动态方法来根据所需的语言环境设置变量。
【解决方案3】:

给定的解决方案有效,但最终为 Euro 留下了一些空格。 我最终做了:

numberFormat.format(myNumber).replaceAll("[^0123456789.,]","");

这可以确保我们对没有货币或任何其他符号的数字具有货币格式。

【讨论】:

  • 爱我一些正则表达式。使用像 replaceAll 这样简单的东西的好解决方案,同时仍然能够考虑多种格式
  • 您可能希望为负数保留减号(以及括号)。 currencyString.replaceAll("[^0123456789.,()-]","")
【解决方案4】:

只需使用NumberFormat.getInstance() 而不是NumberFormat.getCurrencyInstance(),如下所示:

val numberFormat = NumberFormat.getInstance().apply {
    this.currency = Currency.getInstance()
}

val formattedText = numberFormat.format(3.4)

【讨论】:

  • 这将返回一个值 #.# 而 getCurrencyInstance() 返回 #.##
【解决方案5】:

也许我们可以只使用替换或子字符串来获取格式化字符串的数字部分。

NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.getDefault());
fmt.format(-1989.64).replace(fmt.getCurrency().getSymbol(), "");
//fmt.format(1989.64).substring(1);  //this doesn't work for negative number since its format is -$1989.64

【讨论】:

    【解决方案6】:

    我仍然看到有人在 2020 年回答这个问题,所以为什么不呢

    NumberFormat nf = NumberFormat.getInstance(Locale.US);
    nf.setMinimumFractionDigits(2); // <- the trick is here
    System.out.println(nf.format(1000)); // <- 1,000.00
    

    【讨论】:

      【解决方案7】:
      DecimalFormat df = new DecimalFormat();
      df.setMinimumFractionDigits(2);
      String formatted = df.format(num);
      

      适用于num 的多种类型,但不要忘记represent currency with BigDecimal

      对于您的num 可以在小数点后多于两位的情况,您可以使用df.setMaximumFractionDigits(2) 仅显示两位,但这只能对运行该应用程序的人隐藏一个潜在的问题。

      【讨论】:

        【解决方案8】:

        两行答案

        NumberFormat formatCurrency = new NumberFormat.currency(symbol: "");
        var currencyConverted = formatCurrency.format(money);
        

        在文本视图中

        new Text('${formatCurrency.format(money}'),
        

        【讨论】:

          【解决方案9】:

          此处提供的大多数(全部?)解决方案在较新的 Java 版本中无用。请使用这个:

          DecimalFormat formatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.forLanguageTag("hr"));
          formatter.setNegativeSuffix(""); // does the trick
          formatter.setPositiveSuffix(""); // does the trick
          
          formatter.format(new BigDecimal("12345.12"))
          

          【讨论】:

            【解决方案10】:
            NumberFormat numberFormat  = NumberFormat.getCurrencyInstance(Locale.UK);
                    System.out.println("getCurrency = " + numberFormat.getCurrency());
                    String number = numberFormat.format(99.123452323232323232323232);
                    System.out.println("number = " + number);
            
            

            【讨论】:

            • 试着解释一下你的解决方案,用户代码有什么问题,你做了什么来解决它。
            【解决方案11】:

            这里是任何符号(m2、货币、公斤等)的代码

            fun EditText.addCurrencyFormatter(symbol: String) {
            
               this.addTextChangedListener(object: TextWatcher {
            
                    private var current = ""
            
                    override fun afterTextChanged(s: Editable?) {
                    }
            
                    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                    }
            
                    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            
                        if (s.toString() != current) {
                            this@addCurrencyFormatter.removeTextChangedListener(this)
            
                            val cleanString = s.toString().replace("\\D".toRegex(), "")
                            val parsed = if (cleanString.isBlank()) 0.0 else cleanString.toInt()
            
                            val formatter = DecimalFormat.getInstance()
            
                            val formated = formatter.format(parsed).replace(",",".")
            
                            current = formated
                            this@addCurrencyFormatter.setText(formated + " $symbol")
                            this@addCurrencyFormatter.setSelection(formated.length)
            
                            this@addCurrencyFormatter.addTextChangedListener(this)
                        }
                    }
                })
            
            }
            

            -与-一起使用

            edit_text.addCurrencyFormatter("TL")
            

            【讨论】:

              【解决方案12】:

              请尝试以下:

              var totale=64000.15
              var formatter = new Intl.NumberFormat('de-DE');
              totaleGT=new Intl.NumberFormat('de-DE' ).format(totale)
              

              【讨论】:

                【解决方案13】:

                需要一种货币格式“没有符号”,当你得到大量报告或视图并且几乎所有列都代表货币值时,符号很烦人,不需要符号,但对于千位分隔符和十进制逗号是。 你需要

                new DecimalFormat("#,##0.00");
                

                而不是

                new DecimalFormat("$#,##0.00");
                

                【讨论】:

                • 这仅在区域设置为美国、加拿大、澳大利亚等时有用。它不适用于英镑或欧元(某些国家/地区使用小数点而不是逗号作为千位分隔符)。跨度>
                • 这篇文章不是关于使用句号或逗号作为千位分隔符的,你离题了
                • 我仍然得到 DecimalFormat df = new DecimalFormat("#,##0.00");线程“主”java.text.ParseException 中的异常:无法解析的数字:“$400.00”
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2018-03-29
                • 1970-01-01
                • 2010-11-06
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多