programing

float를 문자열로 변환하고 Java에서 float할 문자열

linuxpc 2023. 8. 19. 09:55
반응형

float를 문자열로 변환하고 Java에서 float할 문자열

어떻게 플로트에서 스트링 또는 스트링을 플로트로 변환할 수 있습니까?

나의 경우, 나는 두 개의 값 문자열(테이블에서 얻은 값)과 내가 계산한 float 값 사이에서 어설션을 해야 합니다.

String valueFromTable = "25";
Float valueCalculated =25.0;

저는 처음부터 끝까지 노력했습니다.

String sSelectivityRate = String.valueOf(valueCalculated);

하지만 그 주장은 실패합니다.

Java의 클래스를 사용합니다.

float f = Float.parseFloat("25");
String s = Float.toString(25.0f);

비교하려면 문자열을 float로 변환하고 두 float로 비교하는 것이 좋습니다.이는 하나의 플로트 번호에 대해 여러 문자열 표현이 있으며, 문자열로 비교할 때 다르기 때문입니다(예: "25"!= "25.0"!= "25.00" 등).

문자열로 이동 - String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

문자열과 플로트 연결 - Float.parseFloat()

String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

다음 코드 샘플을 사용해 볼 수 있습니다.

public class StringToFloat
{

  public static void main (String[] args)
  {

    // String s = "fred";    // do this if you want an exception

    String s = "100.00";

    try
    {
      float f = Float.valueOf(s.trim()).floatValue();
      System.out.println("float f = " + f);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("NumberFormatException: " + nfe.getMessage());
    }
  }
}

여기서 발견됨

다음 코드가 도움이 될 것으로 생각합니다.

float f1 = 1.23f;
String f1Str = Float.toString(f1);      
float f2 = Float.parseFloat(f1Str);

이것은 가능한 답입니다. 정확한 데이터도 제공합니다. 필요한 형식으로 소수점을 변경하기만 하면 됩니다.

공용 클래스 Test Standalone {}
/***

이 메서드는 다음을 수행합니다.

@파라미터 void*/public static void main(String[] 인수) {TODO 자동 생성 메서드 스텁시험해 보다플로트 f1=152.32f;Big Decimal 라운드 최종 가격 = 새로운 Big Decimal(f1.float Value()).setScale(2, BigDecimal).라운드_하프_업); System.out.println("f1 --> "+f1"); 문자열 s1=라운드 최종 가격.toPlainString();System.out.println("s1 "+s1");캐치(예외) {TODO 자동 생성 캐치 블록e.printStackTrace();}} }

출력은 다음과 같습니다.

f1 --> 152.32s11 152.32

찾으시는 분들은 소수점 두 자리를 말씀해 주세요. Float f = (float)12.34; String s = new DecimalFormat ("#.00").format (f);

음, 이 방법은 좋은 방법은 아니지만, 쉽고 제안되지 않습니다.아마도 이것이 가장 덜 효과적인 방법이고 더 나쁜 코딩 관행이라고 말해야 할 것 같습니다. 하지만, 사용하는 것은 재미있습니다.

float val=10.0;
String str=val+"";

빈 따옴표를 사용하여 변수 str에 null 문자열을 추가하고 문자열 유형에 'val'을 업캐스팅합니다.

플로트를 문자열로 변환하는 세 가지 방법이 있습니다.

  1. + f
  2. Float.toString(f)
  3. string.valueOf(f)

문자열을 부동으로 변환하는 방법은 두 가지가 있습니다.

  1. Float.valueOf(str)
  2. Float.parseFloat(str);

예:-

public class Test {

    public static void main(String[] args) {
        System.out.println("convert FloatToString " + convertFloatToString(34.0f));

        System.out.println("convert FloatToStr Using Float Method " + convertFloatToStrUsingFloatMethod(23.0f));

        System.out.println("convert FloatToStr Using String Method " + convertFloatToStrUsingFloatMethod(233.0f));

        float f = Float.valueOf("23.00");
    }

    public static String convertFloatToString(float f) {
        return "" + f;
    }

    public static String convertFloatToStrUsingFloatMethod(float f) {
        return Float.toString(f);
    }

    public static String convertFloatToStrUsingStringMethod(float f) {
        return String.valueOf(f);
    }

}
String str = "1234.56";
float num = 0.0f;

int digits = str.length()- str.indexOf('.') - 1;

float factor = 1f;

for(int i=0;i<digits;i++) factor /= 10;

for(int i=str.length()-1;i>=0;i--){

    if(str.charAt(i) == '.'){
        factor = 1;
        System.out.println("Reset, value="+num);
        continue;
    }

    num += (str.charAt(i) - '0') * factor;
    factor *= 10;
}

System.out.println(num);

전체 수동 경로로 이동하기이 방법은 숫자의 소수점을 이동하고 바닥(길이)과 계수를 사용하여 숫자를 추출하여 이중을 문자열로 변환합니다.또한, 소수점이 속한 위치를 파악하기 위해 기저 분할에 의한 계수를 사용합니다.또한 소수점 이후의 위치에 도달하면 숫자의 높은 부분을 "삭제"할 수 있으므로 초대형 더블로 정확도가 떨어지는 것을 방지할 수 있습니다.끝에 주석이 달린 코드를 참조하십시오.제가 테스트한 바로는, 자바 플로트 표현 자체보다 더 정확하지 않습니다. 소수점 이하의 부정확한 자리를 실제로 보여줄 때 말이죠.

/**
 * Convert the given double to a full string representation, i.e. no scientific notation
 * and always twelve digits after the decimal point.
 * @param d The double to be converted
 * @return A full string representation
 */
public static String fullDoubleToString(final double d) {
    // treat 0 separately, it will cause problems on the below algorithm
    if (d == 0) {
        return "0.000000000000";
    }
    // find the number of digits above the decimal point
    double testD = Math.abs(d);
    int digitsBeforePoint = 0;
    while (testD >= 1) {
        // doesn't matter that this loses precision on the lower end
        testD /= 10d;
        ++digitsBeforePoint;
    }

    // create the decimal digits
    StringBuilder repr = new StringBuilder();
    // 10^ exponent to determine divisor and current decimal place
    int digitIndex = digitsBeforePoint;
    double dabs = Math.abs(d);
    while (digitIndex > 0) {
        // Recieves digit at current power of ten (= place in decimal number)
        long digit = (long)Math.floor(dabs / Math.pow(10, digitIndex-1)) % 10;
        repr.append(digit);
        --digitIndex;
    }

    // insert decimal point
    if (digitIndex == 0) {
        repr.append(".");
    }

    // remove any parts above the decimal point, they create accuracy problems
    long digit = 0;
    dabs -= (long)Math.floor(dabs);
    // Because of inaccuracy, move to entirely new system of computing digits after decimal place.
    while (digitIndex > -12) {
        // Shift decimal point one step to the right
        dabs *= 10d;
        final var oldDigit = digit;
        digit = (long)Math.floor(dabs) % 10;
        repr.append(digit);

        // This may avoid float inaccuracy at the very last decimal places.
        // However, in practice, inaccuracy is still as high as even Java itself reports.
        // dabs -= oldDigit * 10l;
        --digitIndex;
    }

    return repr.insert(0, d < 0 ? "-" : "").toString(); 
}

StringBuilder는 속도 향상을 위해 사용되지만, 이 방법은 배열을 사용하기 위해 쉽게 다시 작성될 수 있으므로 다른 언어로도 사용할 수 있습니다.

언급URL : https://stackoverflow.com/questions/7552660/convert-float-to-string-and-string-to-float-in-java

반응형