Read an excerpt from a String

Asked

Viewed 456 times

-4

As you saw my question above, I want to pick up only one part that interests me from a String, for example, I have a String preco whose text is R$ 20,00, how do I take only the number ? Another question is that if I try to add a separate number with a comma and not per point it gives error ?

Many beginners in Java doubt ...

2 answers

4


    public static void main(String []args) throws ParseException {
       String preco = "R$ 20,00";
       //função substring retorna uma nova string apartir do índice passado para ela.
       //a função trim retira espaços que podem porventura ficar na nova String
       String valor = preco.substring(2).trim(); //20,00

       //NumberFormat do Locale default
       NumberFormat nf = NumberFormat.getNumberInstance(new Locale("pt", "BR"));
       //converte um número com vírgulas a partir de uma String para float
       float number = nf.parse(valor).floatValue(); //20.0

       //quando for fazer a soma faça um cast que não ocasionará erro se não colocar o ponto
       float soma = (float) (number + 4.4); //24.4
       float soma1 = (float) (number + 4); //24.0
    }

References

  • 3

    Avoid links as a response, unless they complement a valid response.

  • Following the tips I made modifications to the answer.

-1

Referring to taking a part of a String, you can use a Substring for this. We will also exchange the comma for a point to work in float and perform the desired calculation.

would look this way:

 public static void main(String []args){
    String preco= "R$20,00";
    int um;
    int dois;

    //pega numeros a esquerda da virgula. . .
    um = preco.indexOf("$");
    dois = preco.lastIndexOf(",");
    String precoX = preco.substring(um + 1, dois);
    System.out.println("precoFinal" + precoX.toString());

    //Numeros a direita da Virgula. . .
    um = preco.indexOf(",");
    dois = preco.lastIndexOf(preco.charAt(preco.length() - 1));
    String precoY = preco.substring(um + 1, dois + 1);
    System.out.println("precoFinal" + precoY.toString());

    //Preco pronto para ser convertido. . .
    String precoFinal = OrganizaNumero(precoX, precoY, ".");//até esta etapa, coloquei o ponto no lugar da virgula e tirei o R$ da string. . .


    //converte precoFinal pra float. . .
    float f = Float.parseFloat(precoFinal.toString());

    //soma com outro float. . .
    f = f + 30.50f;

    //transforma novamente em String. . .
    String valorSomado = Float.toString(getFloat(f));
    System.out.println("string" + valorSomado.toString());


 }

 public static float getFloat(float x){return x;}
 public static String organizaNumero(String x, String y, String z){return "" + x.toString() + z.toString() + y.toString();}
  • This does not really answer the two questions of the question.

  • 1

    You took the number but it continues in String, as you would add with another number?

  • I edited the answer. Now it shows how to convert from float to String and vice versa to rerale the calculations and back to String. I converted the comma from the value to a point too, so it can be used in the calculations. If you want to turn the point into a comma again in the result. can do the same way I did at the beginning of the code (take the left and right part of the point and use in the methodNumero)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.