java: converter o 'float' para um texto e o 'String' para um 'float'

Como é que eu poderia converter de float para string ou string para float?

no meu caso, preciso de fazer a afirmação entre a sequência de 2 valores (valor que obtive da tabela) e o valor flutuante que calculei.

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

tentei de float a string:

String sSelectivityRate = String.valueOf(valueCalculated );
Mas a afirmação falha.
Author: RzR, 2011-09-26

10 answers

Usando Java Float classe.

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

Para comparar é sempre melhor converter a cadeia de caracteres para flutuar e comparar como dois flutuadores. Isto é porque para um número flutuante há várias representações de cadeia de caracteres, que são diferentes quando comparados como cadeias (por exemplo, "25" != "25.0" != "25,00" etc.)

 385
Author: Petar Ivanov, 2015-02-28 23:46:37

Flutuar para string-String.valor de ()

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

Texto para flutuar.parseFloat ()

String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)
 33
Author: adatapost, 2011-09-26 08:53:56

Pode tentar esta amostra de código:

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

Encontrei aqui

 5
Author: JMax, 2011-09-26 08:47:21

Acredito que o seguinte código vai ajudar:

float f1 = 1.23f;
String f1Str = Float.toString(f1);      
float f2 = Float.parseFloat(f1Str);
 3
Author: omt66, 2011-09-26 08:48:31

Esta é uma resposta possível, que também irá dar os dados precisos, basta mudar o ponto decimal na forma requerida.

public class TestStandAlone {

    /**
     * 

This method is to main

* @param args void */ public static void main(String[] args) { // TODO Auto-generated method stub try { Float f1=152.32f; BigDecimal roundfinalPrice = new BigDecimal(f1.floatValue()).setScale(2,BigDecimal.ROUND_HALF_UP); System.out.println("f1 --> "+f1); String s1=roundfinalPrice.toPlainString(); System.out.println("s1 "+s1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

A saída será

f1 --> 152.32
s1 152.32
 2
Author: Anupam, 2012-11-20 11:06:09
Se estás à procura, diz duas casas decimais.. Float f = (float)12.34; String s = new DecimalFormat ("#.00").format (f);
 2
Author: RichEarle, 2019-05-30 13:03:54
Bem, este método não é bom, mas fácil e não sugerido. Talvez deva dizer que este é o método menos eficaz e a pior prática de codificação, mas, divertido de usar,
float val=10.0;
String str=val+"";

As aspas vazias, adicione um texto nulo à variável str, uptcasting 'val' ao tipo de texto.

 1
Author: Anmol Thukral, 2016-03-24 18:41:43
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);
 0
Author: gpa, 2018-06-12 04:34:24

Existem três maneiras de converter flutuar para cadeia de caracteres.

  1. "" + f
  2. flutuar.toString (f)
  3. fio.valor de (f)

Existem duas formas de converter o texto para flutuar

  1. flutuar.valor de (str)
  2. flutuar.parseFloat (str);

Exemplo:-

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

}
 0
Author: Neeraj Gahlawat, 2020-02-14 09:43:45

Para percorrer a rota manual completa: este método converte-se em cadeias de caracteres, deslocando o ponto decimal do número em torno e usando o andar (para o comprimento) e módulo para extrair os dígitos. Além disso, ele usa a contagem por divisão base para descobrir o lugar onde o ponto decimal pertence. Ele também pode "excluir" partes mais altas do número, uma vez que atinge os lugares após o ponto decimal, para evitar perder precisão com duplos ultra-grandes. Ver código comentado no final. No meu teste, nunca é menos precisa do que as representações flutuantes Java, quando elas realmente mostram essas imprecisas casas decimais inferiores.

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

Note que enquanto StringBuilder é usado para velocidade, este método pode ser facilmente reescrito para usar arrays e, portanto, também trabalhar em outras línguas.

 0
Author: kleines filmröllchen, 2020-10-07 21:26:28