如何在android中将数字转换为货币格式

时间:2017-08-09 13:28:30

标签: android

我希望以货币格式显示我的数字,并按照以下示例显示单独的数字:

1000 -----> 1000

10000 ----->万

100000 -----> 100,000

1000000 ----->百万

由于

12 个答案:

答案 0 :(得分:10)

您需要使用数字格式化程序,如下所示:

NumberFormat formatter = new DecimalFormat("#,###");
double myNumber = 1000000;
String formattedNumber = formatter.format(myNumber);
//formattedNumber is equal to 1,000,000

希望这有帮助!

答案 1 :(得分:4)

使用此:

int number = 1000000000;
String str = NumberFormat.getNumberInstance(Locale.US).format(number);
//str = 1,000,000,000

答案 2 :(得分:4)

货币格式化程序。

    public static String currencyFormat(String amount) {
        DecimalFormat formatter = new DecimalFormat("###,###,##0.00");
        return formatter.format(Double.parseDouble(amount));
    }

答案 3 :(得分:3)

此方法为您提供所需的确切输出:

public String currencyFormatter(String num) {
    double m = Double.parseDouble(num);
    DecimalFormat formatter = new DecimalFormat("###,###,###");
    return formatter.format(m);
}

答案 4 :(得分:2)

尝试以下解决方案:

NumberFormat format = NumberFormat.getCurrencyInstance();
((TextView)findViewById(R.id.text_result)).setText(format.format(result));

该类将返回设备默认货币的格式化程序。

您可以参考此链接获取更多信息:

https://developer.android.com/reference/java/text/NumberFormat.html

答案 5 :(得分:2)

double number = 1000000000.0;
String COUNTRY = "US";
String LANGUAGE = "en";
String str = NumberFormat.getCurrencyInstance(new Locale(LANGUAGE, COUNTRY)).format(number);

//str = $1,000,000,000.00

答案 6 :(得分:2)

这是一个将 Double 转换为货币的 kotlin 扩展(尼日利亚奈拉)

fun Double.toRidePrice():String{
    val format: NumberFormat = NumberFormat.getCurrencyInstance()
    format.maximumFractionDigits = 0
    format.currency = Currency.getInstance("NGN")

    return format.format(this.roundToInt())
}

答案 7 :(得分:1)

使用Formatter类 例如:

String s = (String.format("%,d", 1000000)).replace(',', ' ');

查看: http://developer.android.com/reference/java/util/Formatter.html

答案 8 :(得分:1)

我在我们的应用程序中执行此操作的方式是:

let url = URL(string: "http://beta.json-generator.com/api/json/get/4ytNy-Nv7")

let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
    if error != nil
    {
        print ("ERROR")
    }
    else
    {
        if let content = data
        {
            do
            {
                //Array
                let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                print(myJson)
                let val = myJson["Location"] as? NSDictionary
                print("val=\(val)")


            }
            catch
            {

            }
        }
    }
}
task.resume()

amount.addTextChangedListener(new CurrencyTextWatcher(amount)); 就是这样:

CurrencyTextWatcher

现在,如果您将此观察者添加到public class CurrencyTextWatcher implements TextWatcher { private EditText ed; private String lastText; private boolean bDel = false; private boolean bInsert = false; private int pos; public CurrencyTextWatcher(EditText ed) { this.ed = ed; } public static String getStringWithSeparator(long value) { DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US); String f = formatter.format(value); return f; } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { bDel = false; bInsert = false; if (before == 1 && count == 0) { bDel = true; pos = start; } else if (before == 0 && count == 1) { bInsert = true; pos = start; } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { lastText = s.toString(); } @Override public void afterTextChanged(Editable s) { ed.removeTextChangedListener(this); StringBuilder sb = new StringBuilder(); String text = s.toString(); for (int i = 0; i < text.length(); i++) { if ((text.charAt(i) >= 0x30 && text.charAt(i) <= 0x39) || text.charAt(i) == '.' || text.charAt(i) == ',') sb.append(text.charAt(i)); } if (!sb.toString().equals(s.toString())) { bDel = bInsert = false; } String newText = getFormattedString(sb.toString()); s.clear(); s.append(newText); ed.addTextChangedListener(this); if (bDel) { int idx = pos; if (lastText.length() - 1 > newText.length()) idx--; // if one , is removed if (idx < 0) idx = 0; ed.setSelection(idx); } else if (bInsert) { int idx = pos + 1; if (lastText.length() + 1 < newText.length()) idx++; // if one , is added if (idx > newText.length()) idx = newText.length(); ed.setSelection(idx); } } private String getFormattedString(String text) { String res = ""; try { String temp = text.replace(",", ""); long part1; String part2 = ""; int dotIndex = temp.indexOf("."); if (dotIndex >= 0) { part1 = Long.parseLong(temp.substring(0, dotIndex)); if (dotIndex + 1 <= temp.length()) { part2 = temp.substring(dotIndex + 1).trim().replace(".", "").replace(",", ""); } } else part1 = Long.parseLong(temp); res = getStringWithSeparator(part1); if (part2.length() > 0) res += "." + part2; else if (dotIndex >= 0) res += "."; } catch (Exception ex) { ex.printStackTrace(); } return res; } ,则只要用户输入其号码,观察者就会决定是否需要分隔符。

答案 9 :(得分:1)

我在我的项目中使用了此代码,并且可以正常工作:

>>> trialDict = {'words':'apple', 'number':5, 'words':'banana','number':6, 'words':'cat', 'number':5}
>>> trialDict
{'words': 'cat', 'number': 5}

和定义的类:

fieldnames = ['words', 'number']
trialDict = {'apple': 5, 'banana': 6, 'cat': 5}

with open("Trial.csv", "w+") as f:
    f.write(','.join(fieldnames) + '\n')
    for word, number in trialDict.items():
        f.write(word + ',' + str(number) + '\n')

}

答案 10 :(得分:0)

另一种方法:

NumberFormat format = NumberFormat.getCurrencyInstance();
format.setMaximumFractionDigits(0);
format.setCurrency(Currency.getInstance("EUR"));

format.format(1000000);

通过这种方式,它会根据设备货币的显示设置显示1 000 000 €1,000,000 €

答案 11 :(得分:-1)

您可以使用此小型简单库轻松实现此目的。 https://github.com/jpvs0101/Currencyfy

只要传递任何数字,它就会返回格式化的字符串,就像这样。

currencyfy (500000.78); // $ 500,000.78  //default

currencyfy (500000.78, false); // $ 500,001 // hide fraction (will round off automatically!)

currencyfy (500000.78, false, false); // 500,001 // hide fraction & currency symbol

currencyfy (new Locale("en", "in"), 500000.78); // ₹ 5,00,000.78 // custom locale

它与所有Android版本(包括旧版本)兼容!