如何仅使用强制转换显示数字的前2位小数?

时间:2014-09-07 20:46:58

标签: java casting

Scanner scan = new Scanner (System.in);

System.out.println("Please input a decimal number:");
    double a = scan.nextDouble();  
    int b = (int)a; 
    double answer = (a - b);    

System.out.println("Answer: " + answer);

这就是我所拥有的,但正如所写,它将显示所有的小数部分,我只想要前2位小数。意思是我输入7.239485,我会得到23作为输出。此外,当我只输入2位小数时,我得到一个非常接近的appoximation。含义7.23将返回0.229989898999或类似的东西。

4 个答案:

答案 0 :(得分:1)

这应该做你想要的。

double x = 7.232323;
int y = (int) (x % 1 * 100);

答案 1 :(得分:1)

最好的方法是使用DecimalFormat: http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

new DecimalFormat("0.##").format(answer)

更简单的方法是:

((double) Math.round(answer * 100)) / 100

或自己实现Math.round()(由于这些方法已经存在,这有点难看)

int answer_round = ((double) (int)(answer * 100)) / 100;
if (answer*100 - (int)(answer*100) >= 0.5) { answer_round += 0.01; }

答案 2 :(得分:0)

import java.util.Scanner;

/**
 * @author Davide
 */
public class test {
    public static void main(String[] args) {

        Scanner a = new Scanner(System.in);
        System.out.println("enter the number");
        double b = a.nextDouble();

        System.out.println(findDecimal(b, 2));
    }

    public static int findDecimal(double number, int decimal) {
        return (int) (number % 1 * Math.pow(10, decimal));
    }
}

答案 3 :(得分:0)

Scanner scan = new Scanner (System.in);

System.out.println("Please input a decimal number:");
    double a = scan.nextDouble();  
    int b = (int)a; 
    double answer = (double)(int)(a*100 - b*100)/100;   

System.out.println("Answer: " + answer);