java : converteer float naar String en String naar float

Hoe kan ik van float naar string of string naar float converteren?

In mijn geval moet ik de bewering doen tussen de string met 2 waarden (waarde die ik uit de tabel heb gehaald) en de zwevende waarde die ik heb berekend.

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

Ik heb geprobeerd van float naar string:

String sSelectivityRate = String.valueOf(valueCalculated );

maar de bewering mislukt


Antwoord 1, autoriteit 100%

Java’s Floatgebruiken klas.

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

Om te vergelijken is het altijd beter om de string te converteren naar float en te vergelijken als twee floats. Dit komt omdat er voor één floatgetal meerdere stringrepresentaties zijn, die verschillend zijn als strings worden vergeleken (bijv. “25” != “25.0” != “25.00” etc.)


Antwoord 2, autoriteit 9%

Zweven naar string – String.valueOf()

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

Tekenreeks om te zweven – Float.parseFloat()

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

Antwoord 3

Je kunt dit codevoorbeeld proberen:

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

gevonden


Antwoord 4

Ik ben van mening dat de volgende code helpt:

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

Antwoord 5

Dit is een mogelijk antwoord, dit geeft ook de precieze gegevens, hoeft u alleen maar het decimale punt in het gewenste formulier te wijzigen.

Public Class TestStandalone {
  / **
   * 

Deze methode is in hoofdstuk

* @param args leegte * / openbare statische void hoofd (string [] args) { // TODO automatisch gegenereerde methode stub proberen { Drijf F1 = 152.32F; BigDecimal RoundfinalPRice = Nieuwe BigDecimal (F1.Floatvalue ()). Setscale (2, bigdecimal.round_half_up); System.out.Println ("F1 - & GT;" + F1); String s1 = roundfinalprice.topLAINTRING (); System.out.Println ("S1" + S1); } Catch (uitzondering e) { // TODO automatisch gegenereerd vangstblok e.Printstacktrace (); } } }

Uitgang is

F1 - & GT; 152.32
S1 152.32

Antwoord 6

Als u op zoek bent, zeg dan twee decimalen ..

Float f = (float)12.34;
String s = new DecimalFormat ("#.00").format (f);


Antwoord 7

Nou, deze methode is niet goed, maar eenvoudig en niet aanbevolen. Misschien moet ik zeggen dat dit de minst effectieve methode is en de slechtste codeerpraktijk, maar leuk om te gebruiken,

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

de lege aanhalingstekens, voeg een null-tekenreeks toe aan de variabele str, upcasting ‘val’ aan het tekenreekstype.


Antwoord 8

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

Antwoord 9

Er zijn driemanieren om float naar String te converteren.

  1. “” + f
  2. Float.toString(f)
  3. String.valueOf(f)

Er zijn tweemanieren om String om te zetten in zwevend

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

Voorbeeld:-

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

Antwoord 10

Om de volledige handmatige route te gaan: deze methode converteert verdubbelt naar snaren door het decimale punt van de cijfer om te schakelen en de vloer (tot lang) en modulus te gebruiken om de cijfers te extraheren. Het maakt ook gebruik van het tellen van de basisdivisie om erachter te komen dat de plaats waar het decimale punt behoort. Het kan ook hogere delen van het nummer “verwijderen” zodra het de plaatsen na het decimale punt bereikt, om te voorkomen dat u precisie verliest met ultra-grote doubles. Zie Commentared Code aan het einde. In mijn testen is het nooit minder nauwkeurig dan de Java float-representaties zelf, wanneer ze deze daadwerkelijk lagere decimale plaatsen tonen.

/**
 * 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(); 
}

Merk op dat hoewel StringBuilder wordt gebruikt voor snelheid, deze methode gemakkelijk kan worden herschreven om arrays te gebruiken en daarom ook in andere talen werkt.

Other episodes