我无法在网上找到我的问题的答案,所以这就是我来这里的原因。在java中使用精确长度打印double
我想在Java打印数量与数字例如指定数量:
Length = 10
1.123456789 ==> 1.123456789
123.123456789 ==> 123.1234567
123456.123456789 ==> 123456.1234
我无法在网上找到我的问题的答案,所以这就是我来这里的原因。在java中使用精确长度打印double
我想在Java打印数量与数字例如指定数量:
Length = 10
1.123456789 ==> 1.123456789
123.123456789 ==> 123.1234567
123456.123456789 ==> 123456.1234
另存为串号,并采取从0到10的子现在你可以解析它BA CK,并得到与10位
好了,你可以计算出基于非十进制数的长度的数量:
public String doubleToString(double in) {
int length = (((int) in) + "").length(); //non-decimal length
if (length <= 0 || length > 10) {
//error out? not sure how you wish to handle 11-digit numbers
}
return String.format("%." + (10 - length) + "f", in); //format decimal
}
缩短:
//default to 0 decimals for >10 digits
public String doubleToString(double in) {
return String.format("%." + Math.max(0, (10 - (((int) in) + "").length()) + "f", in);
}
数你可以试试这个:
Double number = 1.123456789;
BigDecimal bigDecimal = new BigDecimal(number).setScale(6, RoundingMode.HALF_EVEN);
System.out.println("double value: " + bigDecimal.doubleValue());
在setScale
方法,你可以点后选择位数。
看来您需要从String
表示的数字中取第一个n
数字。但是,小数分隔符不应该被计为一个数字:
String printNumber(double number, int n) {
String value = String.valueOf(number);
String result = "";
int count = 0;
for (char c : value.toCharArray()) {
if (count == n) break;
if (c != '.') {
count++;
}
result += c;
}
return result;
}
12345678911(十一位数字)呢? – Rogue
我正在尝试不同的格式方法,但目前没有任何工作,并且是的,我需要一个具有精确数字位数的数字。 –