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

JAVA: use entered integer to define decimal places

这是我第一次进入 Whosebug,所以如果有什么问题请告诉我。

我知道如何用 x 个小数显示导入的浮点数。但是如何通过新扫描的整数来定义十进制数的数量呢?

这是我的代码:(当然“%.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);

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

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

在这种情况下,输出为 123,123,即 # 后的零数量。是你想要的点后数字的数量。