mtz
mtz

Reputation: 33

double to string formatting

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

How could I do it?

Regards.

Upvotes: 3

Views: 4024

Answers (2)

dogbane
dogbane

Reputation: 274522

This answer uses a Decimal Formatter. It assumes that the input number is always strictly of the form (-)xx.yyy.

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

Upvotes: 3

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

double yourDouble = 61.9155;
String str = String.valueOf(yourDouble).replace(".", "");

Explanation:

Update:

The OP had some extra conditions (but I don't know exactly with one):

  • negative number -> only two decimals.

    public static String doubleToSpecialString(double d)
    {
        if (d >= 0)
        {
             return String.valueOf(d).replace(".", "");
        } else
        {
             return String.format("%.2f", d).replace(",", "");
        }
    }
    
  • negative number -> one decimal less

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

Upvotes: 8

Related Questions