设置不带货币符号的货币格式

发布于 2024-12-23 05:15:04 字数 187 浏览 2 评论 0原文

我正在使用 NumberFormat.getCurrencyInstance(myLocale) 来获取我给定的区域设置的自定义货币格式。但是,这始终包含我不想要的货币符号,我只想为给定的区域设置提供正确的货币数字格式,而无需货币符号。

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

I am using NumberFormat.getCurrencyInstance(myLocale) to get a custom currency format for a locale given by me. However, this always includes the currency symbol which I don't want, I just want the proper currency number format for my given locale without the currency symbol.

Doing a format.setCurrencySymbol(null) throws an exception..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

旧故 2024-12-30 05:15:04

以下作品。它有点难看,但它履行了合同:

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));

The following works. It's a bit ugly, but it fulfils the contract:

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

You could also get the pattern from the currency format, remove the currency symbol, and reconstruct a new format from the new pattern:

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));
可是我不能没有你 2024-12-30 05:15:04

将其设置为空字符串:

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

Set it with an empty string instead:

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
初见你 2024-12-30 05:15:04

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

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

val formattedText = numberFormat.format(3.4)

Just use NumberFormat.getInstance() instead of NumberFormat.getCurrencyInstance() like follows:

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

val formattedText = numberFormat.format(3.4)
生死何惧 2024-12-30 05:15:04

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

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

这确保我们拥有数字的货币格式,而无需货币或任何其他符号。

The given solution worked but ended up lefting some whitespaces for Euro for example.
I ended up doing :

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

This makes sure we have the currency formatting for a number without the currency or any other symbol.

寒尘 2024-12-30 05:15:04

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

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

I still see people answering this question in 2020, so why not

NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMinimumFractionDigits(2); // <- the trick is here
System.out.println(nf.format(1000)); // <- 1,000.00
故笙诉离歌 2024-12-30 05:15:04

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

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

Maybe we can just use replace or substring to just take the number part of the formatted string.

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
倾城泪 2024-12-30 05:15:04
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
String formatted = df.format(num);

适用于 num 的多种类型,但不要忘记 用 BigDecimal 表示货币

对于num小数点后可以有两位以上数字的情况,您可以使用df.setMaximumFractionDigits(2)只显示两位,但这只能隐藏来自运行该应用程序的人的根本问题。

DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
String formatted = df.format(num);

Works with many types for num, but don't forget to represent currency with BigDecimal.

For the situations when your num can have more than two digits after the decimal point, you could use df.setMaximumFractionDigits(2) to show only two, but that could only hide an underlying problem from whoever is running the application.

清醇 2024-12-30 05:15:04

这里提供的大多数(全部?)解决方案在较新的 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"))

Most (all?) solutions provided here are useless in newer Java versions. Please use this:

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

formatter.format(new BigDecimal("12345.12"))
澜川若宁 2024-12-30 05:15:04

两行答案

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

TextView 中的

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

Two Line answer

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

In TextView

new Text('${formatCurrency.format(money}'),
向日葵 2024-12-30 05:15:04
NumberFormat numberFormat  = NumberFormat.getCurrencyInstance(Locale.UK);
        System.out.println("getCurrency = " + numberFormat.getCurrency());
        String number = numberFormat.format(99.123452323232323232323232);
        System.out.println("number = " + number);

NumberFormat numberFormat  = NumberFormat.getCurrencyInstance(Locale.UK);
        System.out.println("getCurrency = " + numberFormat.getCurrency());
        String number = numberFormat.format(99.123452323232323232323232);
        System.out.println("number = " + number);

丶情人眼里出诗心の 2024-12-30 05:15:04

这里的代码与任何符号(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) {
                [email protected](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
                [email protected](formated + " $symbol")
                [email protected](formated.length)

                [email protected](this)
            }
        }
    })

}

一起使用-

edit_text.addCurrencyFormatter("TL")

here the code that with any symbol (m2, currency, kilos, etc)

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) {
                [email protected](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
                [email protected](formated + " $symbol")
                [email protected](formated.length)

                [email protected](this)
            }
        }
    })

}

-use with-

edit_text.addCurrencyFormatter("TL")
征﹌骨岁月お 2024-12-30 05:15:04

在这样的函数中

 fun formatWithoutCurrency(value: Any): String {
    val numberFormat = NumberFormat.getInstance()
    return numberFormat.format(value)
}

In a function like this

 fun formatWithoutCurrency(value: Any): String {
    val numberFormat = NumberFormat.getInstance()
    return numberFormat.format(value)
}
瘫痪情歌 2024-12-30 05:15:04

这对我有用。它显示它针对一种语言环境进行了硬编码,但您可以传入任何语言环境,因为两个 NumberFormat 构造函数都使用相同的语言环境(和 currency):

const locale = 'en-US';
const currency = 'USD';

const getCurrencySymbol = () =>
  (0)
    .toLocaleString(locale, {
      style: 'currency',
      currency: currency,
      maximumFractionDigits: 0,
      minimumFractionDigits: 0,
    })
    .replace(/\d/g, '')
    .trim();

const formattedNumberWithoutSymbol = new Intl.NumberFormat(locale, {
  style: 'currency',
  currency: currency,
}).format(499.99).replace(getCurrencySymbol(), '');

console.log(formattedNumberWithoutSymbol);

This does the trick for me. It shows it hardcoded for one locale, but you could pass in any locale as as both NumberFormat constructors use the same locale (and currency):

const locale = 'en-US';
const currency = 'USD';

const getCurrencySymbol = () =>
  (0)
    .toLocaleString(locale, {
      style: 'currency',
      currency: currency,
      maximumFractionDigits: 0,
      minimumFractionDigits: 0,
    })
    .replace(/\d/g, '')
    .trim();

const formattedNumberWithoutSymbol = new Intl.NumberFormat(locale, {
  style: 'currency',
  currency: currency,
}).format(499.99).replace(getCurrencySymbol(), '');

console.log(formattedNumberWithoutSymbol);
病女 2024-12-30 05:15:04

看起来是一个更干净的解决方案,不会以一种黑客的方式改变货币符号:

val numberFormat = NumberFormat.getNumberInstance().apply {
    val priceFormat = NumberFormat.getCurrencyInstance()
    minimumFractionDigits = priceFormat.minimumFractionDigits
    maximumFractionDigits = priceFormat.maximumFractionDigits
}

出于某种原因,使用 Currency.getInstance() 在 NumberFormat 中设置货币对我来说不起作用。

Looks like a cleaner solution that doesn't alter the currency symbol in a hacky way:

val numberFormat = NumberFormat.getNumberInstance().apply {
    val priceFormat = NumberFormat.getCurrencyInstance()
    minimumFractionDigits = priceFormat.minimumFractionDigits
    maximumFractionDigits = priceFormat.maximumFractionDigits
}

For some reason, setting the currency in NumberFormat with Currency.getInstance() didn't work for me.

一身仙ぐ女味 2024-12-30 05:15:04

需要“没有符号”的货币格式,当您收到大量报告或视图并且几乎所有列都代表货币值时,该符号很烦人,不需要该符号,但是是的用于千位分隔符和小数点逗号。
你需要

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

和不需要

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

there is a need for a currency format "WITHOUT the symbol", when u got huge reports or views and almost all columns represent monetary values, the symbol is annoying, there is no need for the symbol but yes for thousands separator and decimal comma.
U need

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

and not

new DecimalFormat("$#,##0.00");
梦情居士 2024-12-30 05:15:04

请尝试以下:

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

Please try below:

var totale=64000.15
var formatter = new Intl.NumberFormat('de-DE');
totaleGT=new Intl.NumberFormat('de-DE' ).format(totale)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文