3

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.

2 Answers 2

8
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(",", "");
        }
    }
    
Sign up to request clarification or add additional context in comments.

9 Comments

doesn't work for negative numbers. xx.yyy needs to become -xxyy, according to the question.
but what happens if the value is negative (-26.301), i'll get a 5 character length plus the sign ("-26301"), and I need only 4 plus the sign ("-2630").
@mtz: So, if it is a negative you only want two decimals or only 4 numbers?
The resulting string must be 5 characters in length. If the value is POSITIVE the two first digits are the integral part, the remaining three are the decimal part. If the value is NEGATIVE, the two first digits are the integral part, the remaining two are the decimal part and the first character is the negative sign.
@mtz: Alright! So you are sure that the double is always exactly in that format...
|
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.