JAVA:使用输入的整数来定义小数位

时间:2015-10-07 18:01:30

标签: java decimal

这是我第一次进入stackoverflow,所以如果出现问题请告诉我。

我知道如何显示带有x十进制数的导入浮点数。但是,如何通过新扫描的int数定义十进制数量?

这是我的代码:(当然"%。小数"不工作,我只想测试它)

任何人?提前致谢!

import java.util.Scanner;

public class Fliesskommazahl{

  public static void main (String[] args){

    // ask for/import floating point number
    System.out.println("Please enter a floating point number like 1,1234: ");
    Scanner scanner = new Scanner(System.in);
    float number = scanner.nextFloat();

    // show floating point number
    System.out.println("You've entered: " + number);

    /* show number with exactly two decimal places
       In short, the %.02f syntax tells Java to return your variable (number) with 2 decimal places (.2)
       in decimal representation of a floating-point number (f) from the start of the format specifier (%).
    */
    System.out.println("Your number with two decimal places: ");
    System.out.printf("%.02f", number);
    System.out.println();

    // import second (positive) number.
    System.out.println("Please enter a positive integer number to define amount of decimal places: ");
    Scanner scanner2 = new Scanner(System.in);
    int decimal = scanner.nextInt();

    // show imported floating point number with imported number of decimal places.

    System.out.printf("%.decimalf", number);



  }
}

2 个答案:

答案 0 :(得分:1)

这可行吗

System.out.printf ("%." + decimal + "f", number);

答案 1 :(得分:0)

你应该使用这个课程我认为这对你来说真的很有用:

double num = 123.123123123;
DecimalFormat df = new DecimalFormat("#.000");
System.out.println(df.format(num));

在这种情况下,输出将是123,123,即#之后的零。是点后的数字量。