Remove 2 specific characters from a String

4

Good afternoon! Devs, I can not solve the following problem: In a calculator app, the calculations always return a Double, which automatically inserts a decimal even if it is to deploy zero, and to show in the editText would like to remove the ".0" when it would show 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 command to EditText.setText ("7.0");

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

private String convertInt(Double duplo){
    return String.valueOf(duplo).replace(".0", "");
}
    
asked by anonymous 27.11.2018 / 21:26

3 answers

3

Hello, here's a simple algorithm with comments to make it easier to understand:

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!

    
27.11.2018 / 22:33
3

Hello, my friend! Home You can use DecimalFormat . Example:

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

I hope I have helped.

Hugs,

    
27.11.2018 / 22:29
1

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

You have missed placing a string end anchor in replace and also escaping the meta-character point. By default, replace will replace the first snippet that matches the last pattern. To force replace only .0 at the end, we need to do the following:

  • escape the backslash \
  • by the end-of-line anchor $
  • Since Java (pre-12) always interprets the string, replacing the escapes, so we need to escape the backslash. The default looks like this:

    "\.0$"
    

    Then the entire call of replace looks like this:

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

    If you are going to use raw strings for Java 12 (which will be released on March 2019), the code looks like this:

    stringValue.replace('\.0$', "");
    
        
    28.11.2018 / 19:43