如何在数字之间添加逗号

时间:2014-02-04 18:16:57

标签: android comma

我的计算器有这个代码:

            public void onClick(View v) {

            try {

                double price = Double.parseDouble(InputPrice.getText()
                        .toString());
                double percent = Double.parseDouble(InputPercent.getText()
                        .toString());

                double priceValue = price * percent / 100.0f;
                double percentValue = price - priceValue;

                PriceToGet.setText(String.valueOf(priceValue));
                PriceToPay.setText(String.valueOf(percentValue));

                PriceToGet.setText(String.format("%.02f", priceValue));
                PriceToPay.setText(String.format("%.02f", percentValue));

输入和输出没有这样的逗号:

输入:333333333

输出:134555.44

输出:17475.66

这只是输出和输入的一个例子。

我希望用户看到它们是:

输入:333,333,333

输出:134,555.44

输出:17,475.66

由于

更新

我在onclick代码中添加了decimal:

                    DecimalFormat formatter = new DecimalFormat("#,###,###"); 

我使用了这段代码,但在按下按钮后关闭了应用程序:

                    String PriceToGet = formatter.format(String.format("%.02f", priceValue));

当我使用这种方法时:

                    String PriceToGet = formatter.format("%.02f", priceValue);

它强迫我改变它:

String PriceToGet = formatter.format(priceValue);

怎么办?

3 个答案:

答案 0 :(得分:2)

您需要使用DecimalFormat

您将找到完整的答案here

答案 1 :(得分:2)

这是你可以将一个整数转换为字符串的方法。

int x = 1000000;
DecimalFormat formatter = new DecimalFormat("#,###,###"); 
String number_string = formatter.format(x);
System.out.println(number_string);
// Outputs 1,000,000

答案 2 :(得分:-3)

来自Css Tricks的这个JS函数 - http://css-tricks.com/snippets/javascript/comma-values-in-numbers/

 function CommaFormatted(amount) {
    var delimiter = ","; // replace comma if desired
    var a = amount.split('.',2)
    var d = a[1];
    var i = parseInt(a[0]);
    if(isNaN(i)) { return ''; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while(n.length > 3) {
        var nn = n.substr(n.length-3);
        a.unshift(nn);
        n = n.substr(0,n.length-3);
    }
    if(n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    if(d.length < 1) { amount = n; }
    else { amount = n + '.' + d; }
    amount = minus + amount;
    return amount;
}
相关问题