Remove 2 specific characters from a String

Asked

Viewed 1,697 times

4

Good afternoon ! Devs, I’m having trouble solving the following problem: In a calculator app, calculations always return a Double, which automatically inserts a decimal place even if it is to deploy zero, and to show in editText I would like to remove the ". 0" when displaying the result; for example: the calculate function returns a double in this call: sum(3, 4) returns 7.0; this return I convert to String and send to Edittext.setText("7.0");

What I need is: create an algorithm that checks the last two chars of that string, if they are equal to ". 0", then I return the string without them, with an replace for example, but only if these are exactly the last two characters: This is what I have so far, but if the value is "100.07" it returns erroneously "1007";

private String convertInt(Double duplo){
    return String.valueOf(duplo).replace(".0", "");
}
  • Simply put, what Cvoce wants is: Transforms double into string<br> Substring of last 2 characters<br> Transforms into int<br> Verifies if greater than zero:<br> yes -> printa original variable<br> not -> printa the cropped

3 answers

4

Hey, buddy!
You can use the Decimalformat.
Example:

Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

I hope I’ve helped.

Hugs,

2


Hello, below is a simple algorithm with comments to facilitate understanding:

String convertInt(Double duplo){
    String sDouble = Double.toString(duplo); //Convertendo para String para retornar uma String adaptando ao seu contexto.

    StringBuilder doisUltimosCharacteres = new StringBuilder(); //StringBuilder representativo apenas para pegarmos os 2 últimos caracteres do valor recebido como parâmetro

    doisUltimosCharacteres.append(sDouble.charAt(sDouble.length() -2 )); //Pega o penultimo valor da String...
    doisUltimosCharacteres.append(sDouble.charAt(sDouble.length() -1)); //... e concatena com o último para verificarmos se esses dois ultimos caracteres são '.0'

    if(doisUltimosCharacteres.toString().equals(".0")){ //Aqui validamos se os dois ultimos caracteres são '.0', se for, retornamos o valor como desejado  
        return sDouble.substring(0, sDouble.length() -2);
    }

    return sDouble; //retorna o valor enviado por parâmetro sem modificações.
}

Good studies!

2

The solution using the DecimalFormat is the most appropriate. However, if you want to treat using String purely, so we can use the replace with the appropriate regular expression pattern.

He missed putting a string end anchor on replace and also escape the point meta-character. By default, the replace will replace the first chunk that matches the pattern passed. To force replace only the .0 in the end, we need to do the following:

  1. escape the point with backslash \
  2. by the end of line anchor $

Since Java (prior to 12) always interprets the string, replacing the escapes, then we need to escape the backslash. The pattern looks like this:

"\\.0$"

So the whole call from replace gets like this:

stringValue.replace("\\.0$", "");

If you’re going to use raw strings java 12 (which will be released in March/2019), the code would look like this:

stringValue.replace(`\.0$`, "");

Browser other questions tagged

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