programing

Java를 사용하여 과학적 표기법을 사용하지 않고 이중 값을 인쇄하려면 어떻게 해야 합니까?

coolbiz 2022. 8. 27. 23:50
반응형

Java를 사용하여 과학적 표기법을 사용하지 않고 이중 값을 인쇄하려면 어떻게 해야 합니까?

자바에서 지수 형식을 사용하지 않고 더블 값을 출력하고 싶습니다.

double dexp = 12345678;
System.out.println("dexp: "+dexp);

E표기는 '나다 E표기' 입니다.1.2345678E7.

요.12345678

이것을 예방하는 가장 좋은 방법은 무엇입니까?

Java foreve E 표기법 이중화:

더블을 일반 수치로 변환하는 방법에는 5가지가 있습니다.

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: " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "★★★★★★★★★★★★★★★★★★★★★★★★?0.1+0.20.30000000000001

http://youtube.com/watch?v=PZRI1IfStY0

하면 .printf()%f:

double dexp = 12345678;
System.out.printf("dexp: %f\n", dexp);

인쇄가 됩니다.dexp: 12345678.000000, 단수가 경우,

System.out.printf("dexp: %.0f\n", dexp);

in 0 ( 0 )%.0f단수가 0자리, 즉 단수가 없음을 의미합니다. 이하 부분 0이 해 주세요.%.8f디폴트로는 소수점 이하 6자리까지 소수점 이하가 인쇄됩니다.

이것은 매뉴얼에 설명되어 있는 형식 지정 언어를 사용합니다.

" " "toString()여기에 원래의 코드에 사용된 포맷이 기재되어 있습니다.

요컨대:

후행 제로 및 로케일의 문제를 해소하려면 , 다음의 방법을 사용할 필요가 있습니다.

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^72보다^-3보다 크거나 을 사용합니다.
  • 「」를 사용해 .%f10시 6시 6초그렇지 않으면 하드코드를 할 수 있지만 소수점 이하일 경우 0이 추가됩니다.§:

    double myValue = 0.00000021d;
    String.format("%.12f", myvalue); // Output: 0.000000210000
    
  • 「」를 사용해 .setMaximumFractionDigits(0); ★★★★★★★★★★★★★★★★★」%.0f소수 정밀도를 제거합니다. 이는 정수/길이에는 해당되지만 두 배에는 해당되지 않습니다.

    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
    
  • DecimalFormat을 사용하면 로컬에 의존하게 됩니다.프랑스어 로케일에서 소수점 구분 기호는 점이 아닌 쉼표입니다.

    double myValue = 0.00000021d;
    DecimalFormat df = new DecimalFormat("0");
    df.setMaximumFractionDigits(340);
    System.out.println(df.format(myvalue)); // Output: 0,00000021
    

    영어 로케일을 사용하면 프로그램이 실행되는 장소에서 소수점 구분자로 포인트를 얻을 수 있습니다.

을 사용하고 , 「340」에 대해서?setMaximumFractionDigits

두 가지 이유:

  • setMaximumFractionDigits정수를 사용할 수 , 그 , 즉 「정수」, 「정수」, 「정수」를 할 수 있습니다.DecimalFormat.DOUBLE_FRACTION_DIGITS
  • Double.MIN_VALUE = 4.9E-324따라서 340자리 숫자를 사용하더라도 두 배의 반올림이나 정확도가 저하되지 않습니다.

도 같이 수 있어요.DecimalFormat이 클래스에서는 숫자를 매우 유연하게 해석할 수 있습니다.
사용할 패턴을 정확하게 설정할 수 있습니다.
예를 들어 다음과 같습니다.

double test = 12345678;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(0);
System.out.println(df.format(test)); //12345678

BigDecimal의 toPlainString()과 관련된 다른 솔루션이 있는데, 이번에는 javadoc에서 권장하는 String-constructor를 사용합니다.

이 생성자는 Float.toString 및 Double.toString에서 반환되는 값과 호환됩니다.이것은 일반적으로 BigDecimal(double) 컨스트럭터의 예측 불가능성에 영향을 받지 않기 때문에 플로트 또는 더블을 BigDecimal로 변환하는 데 선호되는 방법입니다.

가장 짧은 형태로는 다음과 같습니다.

return new BigDecimal(myDouble.toString()).stripTrailingZeros().toPlainString();

NaN 및 무한값은 추가로 체크해야 합니다.따라서 완전한 형태로 보면 다음과 같습니다.

public static String doubleToString(Double d) {
    if (d == null)
        return null;
    if (d.isNaN() || d.isInfinite())
        return d.toString();

    return new BigDecimal(d.toString()).stripTrailingZeros().toPlainString();
}

Float와 잘 작동하도록 복사/붙여넣을 수도 있습니다.

Java 7 이하에서는 제로 값의 Doubles에 대해 "0.0"이 되므로 다음을 추가해야 합니다.

if (d.doubleValue() == 0)
    return "0";

이것은, 번호가 정수인 한 유효합니다.

double dnexp = 12345678;
System.out.println("dexp: " + (long)dexp);

이중 변수가 소수점 이후의 정밀도를 가질 경우 해당 변수는 소수점을 잘라냅니다.

Java/Kotlin 컴파일러는 99999보다 큰 값(1000만 이상)을 과학적 표기법(즉, 과학적 표기법)으로 변환합니다.Epsilion 표기법

예: 12345678은 1.2345678E7로 변환됩니다.

과학적 표기법으로 자동 변환되지 않도록 하려면 다음 코드를 사용합니다.

fun setTotalSalesValue(String total) {
        var valueWithoutEpsilon = total.toBigDecimal()
        /* Set the converted value to your android text view using setText() function */
        salesTextView.setText( valueWithoutEpsilon.toPlainString() )
    }

이중으로 환산할 필요가 있었는데, 대부분의 솔루션은 괜찮았지만, 저는 그렇지 않았습니다.

DecimalFormat이치노 이치노력하다

   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);
    }

보시다시피 자연수라면 소수점 없이 2E7(등)이 아닌 - 20000000을 얻을 수 있습니다.

소수점이라면 소수점 두 자리밖에 안 나와요

다음 코드는 제공된 번호가 과학적 표기법으로 표시되는지 여부를 감지합니다.이 경우 최대 '25'자리의 일반 표시로 표시됩니다.

 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);
}

모두가 옳은 생각을 가지고 있었다고 생각하지만, 모든 답이 간단하지는 않았다.이게 아주 유용한 코드라는 걸 알 수 있어요.기능하는 기능의 일부를 다음에 나타냅니다.

System.out.println(String.format("%.8f", EnterYourDoubleVariableHere));

".8"표시할 소수 자릿수를 설정합니다.

이클립스를 사용하고 있는데 문제없이 작동했어요.

도움이 됐으면 좋겠네요.피드백을 주시면 감사하겠습니다!

이것은 접선일 수 있지만, 시리얼라이저(JSON 등)에 정수로서 너무 큰 값을 넣을 필요가 있는 경우는, 「BigInterger」가 필요하게 됩니다.

예:

value는 문자열 - 7515904334입니다.

Json 메시지에서 수치로 나타낼 필요가 있습니다.

{
    "contact_phone":"800220-3333",
    "servicer_id":7515904334,
    "servicer_name":"SOME CORPORATION"
}

인쇄할 수 없습니다.그렇지 않으면, 다음과 같이 표시됩니다.

{
    "contact_phone":"800220-3333",
    "servicer_id":"7515904334",
    "servicer_name":"SOME CORPORATION"
}

다음과 같은 값을 노드에 추가하면 원하는 결과를 얻을 수 있습니다.

BigInteger.valueOf(Long.parseLong(value, 10))

이것이 실제로 토픽에서는 잘 모르겠습니다만, 이 질문은 제가 솔루션을 검색할 때 가장 큰 히트를 쳤기 때문에, 저는 다른 사람의 이익을 위해 여기서 공유하고, 검색이 서투른 저를 속이고 싶습니다. : D

수학의 문자열 입력으로 사용할 때 생산 코드에 이와 같은 문제가 있었습니다."x + 20 / 50"과 같은 문자열을 사용하는 Eval() 함수

수백 개의 기사를 봤는데...결국 속도 때문에 이렇게 했어요.왜냐하면 Eval 함수는 결국 그것을 고유의 숫자 형식과 수학으로 다시 변환하기 때문입니다.Eval()은 다른 메서드가 반환한 E-07의 후행은 지원하지 않았고, 5dp를 초과하는 것은 어쨌든 내 어플리케이션에는 너무 상세했습니다.

이것은 현재 1,000명 이상의 사용자가 있는 애플리케이션의 프로덕션 코드에 사용되고 있습니다.

double value = 0.0002111d;
String s = Double.toString(((int)(value * 100000.0d))/100000.0d); // Round to 5 dp

s display as:  0.00021

사용하다String.format ("%.0f", number)

소수점 0의 경우 %.0f

String numSring = String.format ("%.0f", firstNumber);
System.out.println(numString);

a로 표시되는 정수값의 경우double다른 솔루션보다 훨씬 빠른 이 코드를 사용할 수 있습니다.

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, this is the best
        DecimalFormat df = 
            new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
        df.setMaximumFractionDigits(340); // 340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
        return df.format(d);
    }
}

// Java 8+
public static boolean isMathematicalInteger(final double d) {
    return StrictMath.rint(d) == d && Double.isFinite(d);
}

솔루션:String str = String.포맷("%.0f", 당신의 Double);

언급URL : https://stackoverflow.com/questions/16098046/how-do-i-print-a-double-value-without-scientific-notation-using-java

반응형