简体   繁体   English

如何使用 DecimalFormat 对数字进行舍入和缩放

[英]How to round and scale a number using DecimalFormat

I'm trying to to format a number using the DecimalFormat but the problem that I didn't get the expected result.我正在尝试使用DecimalFormat格式化数字,但问题是我没有得到预期的结果。 Here is the problem:这是问题所在:

I have this number: 1439131519 and I want to print only the five first digits but with a comma after 4 digits like this: 1439,1 .我有这个号码: 1439131519 ,我只想打印前五个数字,但在 4 位数字后加逗号,如下所示: 1439,1 I have tried to use DecimalFormat but it didn't work.我曾尝试使用 DecimalFormat 但它没有用。

I tried like this but it dosen't work:我试过这样但它不起作用:

 public static DecimalFormat format2 = new DecimalFormat("0000.0"); 

Anyone have an idea?有人有想法吗?

It is easier to do with maths rather than formatting.使用数学而不是格式化更容易。

Assuming your number is in a double:假设您的号码是双倍的:

double d = 1439131519;
d = d / 100000;      // d = 14391,31519
d = Math.round(d)    // d = 14391
d = d / 10;          // d = 1439,1

Of course, you can do it in one line of code if you want.当然,如果需要,您可以在一行代码中完成。 In using Math.round I am assuming you want to round to the nearest value.在使用 Math.round 我假设你想四舍五入到最接近的值。 If you want to round down you can use Math.floor.如果你想四舍五入,你可以使用 Math.floor。

The comma is the normal decimal separator in much of Europe, so that might work by default in your locale.逗号是欧洲大部分地区的正常小数分隔符,因此默认情况下在您的语言环境中可能会起作用。 If not, you can force it by getting the formatter for a locale such as Germany.如果没有,您可以通过获取诸如德国之类的语言环境的格式化程序来强制它。 See: How to change the decimal separator of DecimalFormat from comma to dot/point?请参阅: 如何将 DecimalFormat 的小数分隔符从逗号更改为点/点? . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM