我想用Java將小數列印到特定長度的空間中。但是長度會在演算法運行時定義,所以我不能使用直接格式,例如:
System.out.printf("%8.1f)
例如,長度“8”將在代碼運行時在其他地方定義,我如何配置它以使其自動取決于代碼?
uj5u.com熱心網友回復:
試試這個,你的格式是由代碼中定義的一些“長度”決定的:
double x = 5.2375484914759291;
int length = 8;
String format = "%." length "f";
System.out.printf(format,x);
//5.23754849 is the output for printf("%.8f",5.2375484914759291)
通過將格式字串連接到您的數字變數,您可以指定格式。以下是格式化 int 寬度的示例:
int y = 247;
int width = 8;
String formatWidth ="%0" width "d";
System.out.printf(formatWidth,y);
//00000247 is the output for printf("d",247)
擴展它以格式化長度和寬度:
double z = 247.7526;
int length = 2;
int width = 8;
String formatBoth = "%0" width "." length "f";
System.out.printf(formatBoth,z);
//00247.75 is the output for printf(".2f",247.7526)
您還可以通過將長度和寬度宣告為字串變數來處理格式化字串,具體取決于您的代碼。
uj5u.com熱心網友回復:
只需使用連接構建字串
int x = 8;
System.out.printf("%" x ".1f\n", 1.123);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/492563.html
上一篇:有什么選項可以將其轉換為字串?
下一篇:換行后在文本框中切片文本
