Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a number to always have a sign and decimal separator [duplicate]

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?

like image 652
Kevin Vuilleumier Avatar asked Sep 08 '14 13:09

Kevin Vuilleumier


People also ask

How do you format the numbers with commas and remove all decimal places?

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.

How do you double only show two decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

How do I format a number to two decimal places in Excel?

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.

How do I restrict double value to two decimal places in Excel?

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.


1 Answers

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.####");
}
like image 73
Dmitry Avatar answered Oct 06 '22 21:10

Dmitry