Hi,
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.
Hi,
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.
double yourDouble = 61.9155;
String str = String.valueOf(yourDouble).replace(".", "");
Explanation:
String.valueOf()
: converts your double to a Stringstr.replace(s1, s2)
: returns a new string equals to str
where all s1
's are replaced by s2
'sUpdate:
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(",", "");
}
}
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;
}