Jeremy B
Jeremy B

Reputation: 863

C# number formatting

I asked a similar question before but now I have a better way of asking it. I am working on a calculator. I need to format my division to 8 decimal places. This is the code I am using, and trying to make a custom format. For some reason it ignores my formatting. Am I doing something wrong in the way I have written this part of the code?

 private void btnDivide_Click(object sender, System.EventArgs e)
    {
        calc.Divide(displayValue);
        newValue = true;
        decimalEntered = false;
        displayValue = calc.CurrentValue;
        txtDisplay.Text = displayValue.ToString(string.Format("{####.########}"));
    }

I also tried this sample with no luck.

 private void btnDivide_Click(object sender, System.EventArgs e)
    {
        calc.Divide(displayValue);
        newValue = true;
        decimalEntered = false;
        displayValue = calc.CurrentValue;
        txtDisplay.Text = displayValue.ToString(string.Format("f8"));
    }

I am not sure if my error is with the way I have written this, or if it is somewhere else in my program but your answer may help me narrow it down.

it is my understanding both of those formats "should" accomplish the same thing. Then again, I'm new.

Upvotes: 0

Views: 1103

Answers (3)

TyCobb
TyCobb

Reputation: 9089

private void btnDivide_Click(object sender, System.EventArgs e)
{
    calc.Divide(displayValue);
    newValue = true;
    decimalEntered = false;
    displayValue = calc.CurrentValue;
    txtDisplay.Text = displayValue.ToString("#,###.########");
}

This change should do what you want. This will format the number to include commas and decimal up to 8 (if needed).

If you want to force 8 decimal places, you can use F8 or change the #s to 0s.

Upvotes: 0

Noctis
Noctis

Reputation: 11763

I think what you wanted is this

 Console.Write(d.ToString("F8"));

This will output 8 digits after the point .

More info here: http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx#FFormatString

Upvotes: 0

josey wales
josey wales

Reputation: 271

I think it's zero instead of #. This code snippet displays 8 decimals for me.

void Main()
{
decimal d = 351.23456M;
Console.Write(d.ToString("0.00000000"));
}

Upvotes: 1

Related Questions