Java를 사용하여 과학적 표기법없이 이중 값을 인쇄하려면 어떻게합니까?
지수 형태없이 Java에서 이중 값을 인쇄하고 싶습니다.
double dexp = 12345678;
System.out.println("dexp: "+dexp);
이 E 표기법을 보여줍니다 1.2345678E7
.
다음과 같이 인쇄하고 싶습니다. 12345678
이것을 방지하는 가장 좋은 방법은 무엇입니까?
printf()
함께 사용할 수 있습니다 %f
:
double dexp = 12345678;
System.out.printf("dexp: %f\n", dexp);
인쇄 dexp: 12345678.000000
됩니다. 소수 부분을 원하지 않으면
System.out.printf("dexp: %.0f\n", dexp);
이것은 문서에 설명 된 형식 지정자 언어를 사용합니다 .
toString()
원래 코드에서 사용되는 기본 형식은 여기에 나와 있습니다 .
Java는 이중으로 E 표기를 방지합니다.
double을 일반 숫자로 변환하는 다섯 가지 방법 :
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Runner {
public static void main(String[] args) {
double myvalue = 0.00000021d;
//Option 1 Print bare double.
System.out.println(myvalue);
//Option2, use decimalFormat.
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(8);
System.out.println(df.format(myvalue));
//Option 3, use printf.
System.out.printf("%.9f", myvalue);
System.out.println();
//Option 4, convert toBigDecimal and ask for toPlainString().
System.out.print(new BigDecimal(myvalue).toPlainString());
System.out.println();
//Option 5, String.format
System.out.println(String.format("%.12f", myvalue));
}
}
이 프로그램은 다음을 인쇄합니다.
2.1E-7
.00000021
0.000000210
0.000000210000000000000001085015324114868562332958390470594167709350585
0.000000210000
모두 같은 값입니다.
Protip : 당신은 그 임의의 숫자가 두 배 값에 특정 임계 값을 초과 표시 이유에 대해 혼동하는 경우,이 비디오는 설명 : computerphile 이유는 무엇입니까 0.1
+ 0.2
같음 0.30000000000001
?
http://youtube.com/watch?v=PZRI1IfStY0
한마디로 :
후행 0과 로케일 문제를 제거하려면 다음을 사용해야합니다.
double myValue = 0.00000021d;
DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); // 340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
System.out.println(df.format(myValue)); // Output: 0.00000021
설명:
다른 답변이 저에게 적합하지 않은 이유 :
Double.toString()
또는System.out.println
또는FloatingDecimal.toJavaFormatString
이중 10 개 미만인 경우 ^ -3 과학적 표기법을 사용하거나보다 큰 10 ^ 7 동등을 사용
%f
하면 기본 10 진수 정밀도는 6이며, 그렇지 않으면 하드 코딩 할 수 있지만 소수가 적 으면 추가 0이 추가됩니다. 예:double myValue = 0.00000021d; String.format("%.12f", myvalue); // Output: 0.000000210000
10 진수 정밀도 를 사용
setMaximumFractionDigits(0);
하거나%.0f
제거하면 정수 / 길이에는 적합하지만 double에는 적합하지 않습니다.double myValue = 0.00000021d; System.out.println(String.format("%.0f", myvalue)); // Output: 0 DecimalFormat df = new DecimalFormat("0"); System.out.println(df.format(myValue)); // Output: 0
By using DecimalFormat, you are local dependent. In French locale, the decimal separator is a comma, not a point:
double myValue = 0.00000021d; DecimalFormat df = new DecimalFormat("0"); df.setMaximumFractionDigits(340); System.out.println(df.format(myvalue)); // Output: 0,00000021
Using the ENGLISH locale makes sure you get a point for decimal separator, wherever your program will run.
Why using 340 then for setMaximumFractionDigits
?
Two reasons:
setMaximumFractionDigits
accepts an integer, but its implementation has a maximum digits allowed ofDecimalFormat.DOUBLE_FRACTION_DIGITS
which equals 340Double.MIN_VALUE = 4.9E-324
so with 340 digits you are sure not to round your double and lose precision.
You can try it with DecimalFormat
. With this class you are very flexible in parsing your numbers.
You can exactly set the pattern you want to use.
In your case for example:
double test = 12345678;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(0);
System.out.println(df.format(test)); //12345678
I've got another solution involving BigDecimal's toPlainString(), but this time using the String-constructor, which is recommended in the javadoc:
this constructor is compatible with the values returned by Float.toString and Double.toString. This is generally the preferred way to convert a float or double into a BigDecimal, as it doesn't suffer from the unpredictability of the BigDecimal(double) constructor.
It looks like this in its shortest form:
return new BigDecimal(myDouble.toString()).stripTrailingZeros().toPlainString();
Pre Java 8, this results in "0.0" for any zero-valued Doubles, so you would need to add:
if (myDouble.doubleValue() == 0)
return "0";
NaN and infinite values have to be checked extra.
The final result of all these considerations:
public static String doubleToString(Double d) {
if (d == null)
return null;
if (d.isNaN() || d.isInfinite())
return d.toString();
// Pre Java 8, a value of 0 would yield "0.0" below
if (d.doubleValue() == 0)
return "0";
return new BigDecimal(d.toString()).stripTrailingZeros().toPlainString();
}
This can also be copied/pasted to work nicely with Float.
This will work as long as your number is a whole number:
double dnexp = 12345678;
System.out.println("dexp: " + (long)dexp);
If the double variable has precision after the decimal point it will truncate it.
I needed to convert some double to currency values and found that most of the solutions were OK, but not for me.
The DecimalFormat
was eventually the way for me, so here is what I've done:
public String foo(double value) //Got here 6.743240136E7 or something..
{
DecimalFormat formatter;
if(value - (int)value > 0.0)
formatter = new DecimalFormat("0.00"); // Here you can also deal with rounding if you wish..
else
formatter = new DecimalFormat("0");
return formatter.format(value);
}
As you can see, if the number is natural I get - say - 20000000 instead of 2E7 (etc.) - without any decimal point.
And if it's decimal, I get only two decimal digits.
Java/Kotlin compiler converts any value greater than 9999999 (greater than or equal to 10 million) to scientific notation ie. Epsilion notation.
Ex: 12345678 is converted to 1.2345678E7
Use this code to avoid automatic conversion to scientific notation:
fun setTotalSalesValue(String total) {
var valueWithoutEpsilon = total.toBigDecimal()
/* Set the converted value to your android view using setText() function */
salesTextView.setText() = valueWithoutEpsilon.toPlainString()
}
The following code detects if the provided number is presented in scientific notation. If so it is represented in normal presentation with a maximum of '25' digits.
static String convertFromScientificNotation(double number) {
// Check if in scientific notation
if (String.valueOf(number).toLowerCase().contains("e")) {
System.out.println("The scientific notation number'"
+ number
+ "' detected, it will be converted to normal representation with 25 maximum fraction digits.");
NumberFormat formatter = new DecimalFormat();
formatter.setMaximumFractionDigits(25);
return formatter.format(number);
} else
return String.valueOf(number);
}
I think everyone had the right idea, but all answers were not straightforward. I can see this being a very useful piece of code. Here is a snippet of what will work:
System.out.println(String.format("%.8f", EnterYourDoubleVariableHere));
the ".8"
is where you set the number of decimal places you would like to show.
I am using Eclipse and it worked no problem.
Hope this was helpful. I would appreciate any feedback!
I had this same problem in my production code when I was using it as a string input to a math.Eval() function which takes a string like "x + 20 / 50"
I looked at hundreds of articles... In the end I went with this because of the speed. And because the Eval function was going to convert it back into its own number format eventually and math.Eval() didn't support the trailing E-07 that other methods returned, and anything over 5 dp was too much detail for my application anyway.
This is now used in production code for an application that has 1,000+ users...
double value = 0.0002111d;
String s = Double.toString(((int)(value * 100000.0d))/100000.0d); // Round to 5 dp
s display as: 0.00021
For integer values represented by a double
, you can use this code, which is much faster than the other solutions.
public static String doubleToString(final double d) {
// check for integer, also see https://stackoverflow.com/a/9898613/868941 and
// https://github.com/google/guava/blob/master/guava/src/com/google/common/math/DoubleMath.java
if (isMathematicalInteger(d)) {
return Long.toString((long)d);
} else {
// or use any of the solutions provided by others
return Double.toString(d);
}
}
// Java 8+
public static boolean isMathematicalInteger(final double d) {
return StrictMath.rint(d) == d && Double.isFinite(d);
}
My solution: String str = String.format ("%.0f", yourDouble);
'Programming' 카테고리의 다른 글
LINQ Single과 First (0) | 2020.05.07 |
---|---|
선택된 단일 선택 단추 레이블에 대한 CSS 선택기 (0) | 2020.05.07 |
R에서 벡터를 청크로 나눕니다. (0) | 2020.05.07 |
여러 테이블에서 개수 (*)를 선택하십시오. (0) | 2020.05.07 |
비활성화 된 입력 값은 제출되지 않습니다 (0) | 2020.05.07 |