相关疑难解决方法(0)

如何在Java中将数字舍入到n个小数位

我想要的是一种将double转换为使用half-up方法进行舍入的字符串的方法 - 即如果要舍入的小数为5,则它总是向上舍入到前一个数字.这是在大多数情况下舍入大多数人所期望的标准方法.

我也希望只显示有效数字 - 即不应该有任何尾随零.

我知道这样做的一种方法是使用该String.format方法:

String.format("%.5g%n", 0.912385);
Run Code Online (Sandbox Code Playgroud)

收益:

0.91239
Run Code Online (Sandbox Code Playgroud)

这很好,但它总是显示5位小数的数字,即使它们不重要:

String.format("%.5g%n", 0.912300);
Run Code Online (Sandbox Code Playgroud)

收益:

0.91230
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用DecimalFormatter:

DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);
Run Code Online (Sandbox Code Playgroud)

收益:

0.91238
Run Code Online (Sandbox Code Playgroud)

但是你可以看到这使用了半均匀舍入.也就是说,如果前一个数字是偶数,它将向下舍入.我想要的是这个:

0.912385 -> 0.91239
0.912300 -> 0.9123
Run Code Online (Sandbox Code Playgroud)

在Java中实现这一目标的最佳方法是什么?

java decimal rounding digits

1209
推荐指数
22
解决办法
155万
查看次数

基本Java所得税

问题:

编写一个程序,提示用户输入其应税收入,然后使用下面的2014年税表计算应缴所得税。用小数点后两位表示税款。

Income tax brackets for single-filers
up to $9075          10%
$9076 - $36900    15%
$36901 - $89350       25%
$89351 - $186350      28%
$186351 - $405100   33%
Run Code Online (Sandbox Code Playgroud)

到目前为止,这就是我所拥有的。我对Java真的很陌生,因此请记住这一点。我的具体问题将在我的代码之后。

import java.util.Scanner;
public class IncomeTax {    


public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        // Prompt the user to enter taxable income
        System.out.print("Enter the amount of taxable income for the year 2014: ");
        double income = input.nextDouble();

        // Compute tax
        double tax = 0;

        if (income <= 9075)
            tax …
Run Code Online (Sandbox Code Playgroud)

java

-2
推荐指数
1
解决办法
1万
查看次数

标签 统计

java ×2

decimal ×1

digits ×1

rounding ×1