Java 打印浮点或双精度的N个小数
写这样的东西最好的方法是什么:Java 打印浮点或双精度的N个小数,java,decimal-point,Java,Decimal Point,写这样的东西最好的方法是什么: Scanner input = new Scanner(System.in); int n = input.nextInt(); double d = 5.123456789123456789; System.out.printf("%.nf", d); 谢谢 格式字符串只是一个可以在运行时创建的字符串。例如 System.out.printf("%." + n + "f", d); 要保留双精度小数位数,可以使用java DecimalFormat 因为只有
Scanner input = new Scanner(System.in);
int n = input.nextInt();
double d = 5.123456789123456789;
System.out.printf("%.nf", d);
谢谢 格式字符串只是一个可以在运行时创建的字符串。例如
System.out.printf("%." + n + "f", d);
要保留双精度小数位数,可以使用java DecimalFormat 因为只有在运行时才知道小数位数,所以您还需要在运行时为DecimalFormat生成to模式 因此:
你想做什么?要打印双d n次吗?请检查NumberFormat和DecimalFormat
int n = 5; // or read in from user input
String decimalFormatPattern = ".";
for (int i =0 ; i < n; ++i) { // generate pattern at runtime
decimalFormatPattern += "#";
}
// format pattern would be .#####
DecimalFormat decimalFormat = new DecimalFormat(decimalFormatPattern);
double d = 5.123456789123456789;
System.out.println(decimalFormat.format(d));