Double line formatting

I have a double value xx.yyy, and I want to convert to the string "xxyyy" or "-xxyy" if the value is negative.

How can i do this?

Sincerely.

+3
source share
2 answers

This answer uses a decimal formatter. It is assumed that the input number always has the form (-) xx.yyy always.

/**
 * Converts a double of the form xx.yyy to xxyyy and -xx.yyy to -xxyy. 
 * No rounding is performed.
 * 
 * @param number The double to format
 * @return The formatted number string
 */
public static String format(double number){
    DecimalFormat formatter = new DecimalFormat("#");
    formatter.setRoundingMode(RoundingMode.DOWN);
    number *= number < 0.0 ? 100 : 1000;
    String result = formatter.format(number);
    return result;
}
+3
source
double yourDouble = 61.9155;
String str = String.valueOf(yourDouble).replace(".", "");

Explanation:

Update

The OP had some additional conditions (but I don’t know for sure with one):

  • → .

    public static String doubleToSpecialString(double d)
    {
        if (d >= 0)
        {
             return String.valueOf(d).replace(".", "");
        } else
        {
             return String.format("%.2f", d).replace(",", "");
        }
    }
    
  • public static String doubleToSpecialString(double d)
    {
        if (d >= 0)
        {
             return String.valueOf(d).replace(".", "");
        } else
        {
             String str = String.valueOf(d);
             int dotIndex = str.indexOf(".");
             int decimals = str.length() - dotIndex - 1;
             return String.format("%." + (decimals - 1) + "f", d).replace(",", "");
        }
    }
    
+8

Source: https://habr.com/ru/post/1764013/


All Articles