java 安卓数字格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5978707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:48:55  来源:igfitidea点击:

android number format

java

提问by upv

In my app want to round a double to 2 significant figures after decimal point. I tried the code below.

在我的应用程序中,想要在小数点后四舍五入到两位有效数字。我尝试了下面的代码。

public static double round(double value, int places) {
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}

also i tried

我也试过

double val = ....;
val = val*100;
val = (double)((int) val);
val = val /100;

both code do not working for me.

两个代码都不适合我。

Thanks in advance....

提前致谢....

回答by Ian McLaird

As Grammin said, if you're trying to represent money, use BigDecimal. That class has support for all sorts of rounding, and you can set you desired precision exactly.

正如 Grammin 所说,如果您想代表金钱,请使用BigDecimal。该类支持各种舍入,您可以准确设置所需的精度。

But to directly answer your question, you can't set the precision on a double, because it's floating point. It doesn't havea precision. If you just need to do this to format output, I'd recommend using a NumberFormat. Something like this:

但是要直接回答您的问题,您不能将精度设置为双精度,因为它是浮点数。它不具有精度。如果您只需要这样做来格式化输出,我建议您使用NumberFormat。像这样的东西:

NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
String output = nf.format(val);

回答by ratchet freak

Or you can use a java.text.DecimalFormat:

或者您可以使用java.text.DecimalFormat

String string = new DecimalFormat("####0.00").format(val);

回答by Grammin

I would recommend using BigDecimalif you are trying to represent currency.

如果您要表示货币,我建议您使用BigDecimal

This examplemay be helpful.

这个例子可能会有所帮助。

回答by Riccardo Cossu

As Gramming suggested you could use BigDecimals for that, or NumberFormat tobe sure about the number of shown figures

正如 Gramming 建议你可以使用 BigDecimals 或 NumberFormat 来确定显示的数字的数量

回答by Jim Blackler

Your code appears to work to me

你的代码似乎对我有用

double rounded = round(0.123456789, 3);
System.out.println(rounded);

>0.123

Edit: just seen your new comment on your question. This is a formatting problem, not a maths problem.

编辑:刚刚看到您对问题的新评论。这是格式问题,不是数学问题。

回答by Boris Karloff

I took the decision to use all as int. In this way no problem.

我决定将 all 用作 int。这样就没有问题了。

DecimalFormatSymbols currencySymbol = DecimalFormatSymbols.getInstance();
NumberFormat numberF = NumberFormat.getInstance();

after...

后...

numberF.setMaximumFractionDigits(2);
numberF.setMinimumFractionDigits(2);

TextView tv_total = findViewById(R.id.total);
int total = doYourStuff();//calculate the prices
tv_total.setText(numberF.format(((double)total)/100) + currencySymbol.getCurrencySymbol());