Programing

Java에서 문자열을 이중 문자열로 변환

c10106 2022. 4. 26. 21:15
반응형

Java에서 문자열을 이중 문자열로 변환

어떻게 변환할 수 있는가?String예를 들어"12.34"완전히double자바에서?

을(를) 변환하는 데 사용할 수 있음String완전히double:

String text = "12.34"; // example String
double value = Double.parseDouble(text);

당신의 경우, 당신이 원하는 것처럼 보인다:

double total = Double.parseDouble(jlbTotal.getText());
double price = Double.parseDouble(jlbPrice.getText());

문자열을 소수점 값으로 구문 분석하는 데 문제가 있으면 숫자에서 ","를 ""로 바꾸어야 한다.


String number = "123,321";
double value = Double.parseDouble( number.replace(",",".") );

문자열을 다시 이중으로 변환하려면 다음 작업을 수행하십시오.

String s = "10.1";
Double d = Double.parseDouble(s);

parseDouble 방법은 원하는 효과를 얻을 것이고, Double.valueOf() 방법도 그럴 것이다.

double d = Double.parseDouble(aString);

이것은 문자열 aString을 더블 d로 변환해야 한다.

사용하다new BigDecimal(string)이것은 나중에 적절한 계산을 보장할 것이다.

경험의 법칙으로 - 항상BigDecimal돈 같은 민감한 계산을 위해

예:

String doubleAsString = "23.23";
BigDecimal price = new BigDecimal(doubleAsString);
BigDecimal total = price.plus(anotherPrice);

더블을 사용하여 문자열 값만 구문 분석하십시오.

String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);

위의 Robertiano의 말을 다시 인용하는 것은 이것이 단연코 가장 다재다능하고 지역적인 적응형 버전이기 때문이다.그것은 완전하게 게시할 가치가 있어!

다른 옵션:

DecimalFormat df = new DecimalFormat(); 
DecimalFormatSymbols sfs = new DecimalFormatSymbols();
sfs.setDecimalSeparator(','); 
df.setDecimalFormatSymbols(sfs);
double d = df.parse(number).doubleValue();
String double_string = "100.215";
Double double = Double.parseDouble(double_string);

다른 방법도 있다.

Double temp = Double.valueOf(str);
number = temp.doubleValue();

더블은 클래스, temp는 변수다."숫자"는 당신이 찾고 있는 마지막 번호다.

이게 내가 할 일이다.

    public static double convertToDouble(String temp){
       String a = temp;
       //replace all commas if present with no comma
       String s = a.replaceAll(",","").trim(); 
      // if there are any empty spaces also take it out.          
      String f = s.replaceAll(" ", ""); 
      //now convert the string to double
      double result = Double.parseDouble(f); 
    return result; // return the result
}

예를 들어 문자열 "4 55,63. 0"을 입력하면 출력이 두 배인 45563.0이 된다.

String s = "12.34";
double num = Double.valueOf(s);

사용.Double.parseDouble()주위가 없이try/catch블록은 전위를 일으킬 수 있다.NumberFormatException입력 이중 문자열이 유효한 형식을 따르지 않는 경우.

Guava는 이를 위한 효용 방법을 제공하고 있다.null문자열을 구문 분석할 수 없는 경우.

https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Doubles.html#tryParse(java.lang.String)

Double valueDouble = Doubles.tryParse(aPotentiallyCorruptedDoubleString);

런타임에 잘못된 형식의 문자열 입력이 생성됨null에 배정된.valueDouble

데이터 유형을 숫자 및 숫자2에서 int로 변환해야 할 때 문자열 번호를 두 배로 변환하는 데 사용 ; Eng:"Bader Qandeel"과 함께 문자열의 두 개에 대한 모든 경우를 처리했다.

public static double str2doubel(String str) {
    double num = 0;
    double num2 = 0;
    int idForDot = str.indexOf('.');
    boolean isNeg = false;
    String st;
    int start = 0;
    int end = str.length();

    if (idForDot != -1) {
        st = str.substring(0, idForDot);
        for (int i = str.length() - 1; i >= idForDot + 1; i--) {
            num2 = (num2 + str.charAt(i) - '0') / 10;
        }
    } else {
        st = str;
    }

    if (st.charAt(0) == '-') {
        isNeg = true;
        start++;
    } else if (st.charAt(0) == '+') {
        start++;
    }

    for (int i = start; i < st.length(); i++) {
        if (st.charAt(i) == ',') {
            continue;
        }
        num *= 10;
        num += st.charAt(i) - '0';
    }

    num = num + num2;
    if (isNeg) {
        num = -1 * num;
    }
    return num;
}

BigDecimal bdVal = 새로운 BigDecimal(str);

Double만 사용하려면 Double d = Double.valueOf(str); System.out.println(String)을 사용해 보십시오.형식("%.3f", 새 BigDecimal(d);

참조URL: https://stackoverflow.com/questions/5769669/convert-string-to-double-in-java

반응형