相关疑难解决方法(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万
查看次数

为什么(360/24)/ 60 = 0 ...在Java中

我正在尝试计算(360/24)/ 60当我得到0.25时,我一直得到答案0.0

用语言:我想将360除以24,然后将结果除以60

public class Divide {

    public static void main(String[] args){
      float div = ((360 / 24) / 60);
      System.out.println(div);

    }
}
Run Code Online (Sandbox Code Playgroud)

打印出:

0.0

这是为什么?我做了一些非常愚蠢的事情,还是有充分理由这样做

java floating-point division

14
推荐指数
2
解决办法
8089
查看次数

main java.lang.ArithmeticException:/ by Zero

我尝试了使用throw new方法来表示不能被零除的不同方法.

public class FractionDemo
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        Fraction f1 = new Fraction(), f2 = new Fraction(); 

        System.out.print("Enter the numerator for the target fraction:"); 
        int a = scan.nextInt(); 

        System.out.print("Enter the denominator for the target fraction:"); 
        int b = scan.nextInt(); 

        System.out.print("Enter the numerator for the next fraction to test:"); 
        int n = scan.nextInt(); 

        System.out.print("Enter the denominator for the next fraction to test:"); 
        int d = scan.nextInt(); 

        if(f1.equals(f2))
            System.out.print("The fraction you just entered …
Run Code Online (Sandbox Code Playgroud)

java

1
推荐指数
1
解决办法
5949
查看次数

标签 统计

java ×3

decimal ×1

digits ×1

division ×1

floating-point ×1

rounding ×1