I want to format any number (integer or real) to a string representation which always has a sign (positive or negative) and a decimal separator, but no trailing zeroes.
Some samples:
3.14 => +3.14
12.00 => +12.
-78.4 => -78.4
-3.00 => -3.
Is it possible with one of the default ToString()
implementations, or do I need write this myself?
Once we click on the “Comma Style,” it will provide the comma-separated format value. If we want to remove the decimal, we must click on the icon under “Number” on “Decrease Decimal.” Once we remove the decimal, we can see below the value without decimals.
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.
By using a button: Select the cells that you want to format. On the Home tab, click Increase Decimal or Decrease Decimal to show more or fewer digits after the decimal point.
Right click the selected cells, and select the Format Cells from the right-clicking menu. 3. In the coming Format Cells dialog box, go to the Number tab, click to highlight the Number in the Category box, and then type a number in the Decimal Places box.
Try something like this:
double x = -12.43;
string xStr = x.ToString("+0.#####;-0.#####");
But this wouldn't help to display trailing decimal point. You can handle such situations using this method:
public static string MyToString(double x)
{
return x == Math.Floor(x)
? x.ToString("+0;-0;0") + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
: x.ToString("+0.####;-0.####");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With