简体   繁体   English

Java中的舍入小数

[英]Rounding Decimals in Java

So, I was making a program, where I have the user insert a numerator and denominator, the program converts the pseudo-fraction, to a decimal. 所以,我正在制作一个程序,我让用户插入分子和分母,程序将伪分数转换为小数。 It works fine, just one thing. 它工作正常,只有一件事。 One, if I enter a fraction that is a repeating decimal, (ex. 1/3, 0.3333333...), I want either it say 0.33 repeat, or for irrational numbers, It would round it after let's say 7 digits, and then stop and have "... Irrational" after. 一,如果我输入一个重复小数的分数(例如,1 / 3,0.3333333 ......),我要么要么说0.33重复,要么是无理数,它会在让我们说7位数之后将其舍入,并且然后停下来,然后“......非理性”。 How could I do this? 我怎么能这样做? Code is below. 代码如下。

package Conversions;

import java.util.*;

public class FractionToDecimal  {

public static void main (String[] args) {
    Scanner sc = new Scanner (System.in);

    System.out.println("Enter Numerator: ");
    int numerator = sc.nextInt();
    System.out.println("Enter Denominator: ");
    int denominator = sc.nextInt();
    if (denominator == 0) {
        System.out.println("Can't divide by zero");
    }
    else {
        double fraction = (double)numerator / denominator;
        System.out.println(fraction);
    }
}
}    

You could use this: 你可以用这个:

DecimalFormat df = new DecimalFormat("#.######");
df.setRoundingMode(RoundingMode.CEILING);

Add as many # as you want decimals and then ou can simply use it like this: 添加尽可能多的# ,你想要小数,然后你可以简单地使用它:

Double d = 12345.789123456;
System.out.println(df.format(d));

Using three # would give you for the example above: 12345.789 for instance. 使用三个#会给你上面的例子:例如12345.789

Please note that you can pick your rounding mode of course. 请注意,您当然可以选择舍入模式。

Small other note: Next time you ask a question on SO, please show some research, there are thousands of post about this and thousands of tutorials online. 小其他注意事项:下次你问一个关于SO的问题,请展示一些研究,有成千上万的关于这个的帖子和数千个在线教程。 It would be nice to show what you have tried, what doesn't work ... 很高兴展示你尝试过的东西,什么不起作用......

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

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