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

我知道如何用x十进制数字显示导入的浮点数。但是,如何通过新的扫描的int数定义小数的数量?
这是我的代码:(当然,“%。decimalf”不起作用,我只想对其进行测试)
任何人?提前致谢!


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);



  }
}

最佳答案

这可以工作

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

10-06 14:57