19

I have an amount field which is a decimal in the database. I need to always display this amount with 10 numbers on the left of the decimal and two after.

Example:
Amount = 245.00 which should display as 0000000245.00 Additionally, the amount could be over 1,000 or 10,000 which should display as:

0000001245.00 and 0000011245.00

How can I format the amount to always have the appropriate number of zeros on the left side of the decimal with a variable amount size?

4 Answers 4

32

You should put 0's in your format string. Something like this.

myValue.ToString("0000000000.00"); 

That will always give you 10 digits on the left side of your decimal point and two on the right.

If you do not want two digits on the right side... do this.

myValue.ToString("0000000000.##"); 

This says hey if we have a value display it; otherwise, skip it.

Sign up to request clarification or add additional context in comments.

1 Comment

This will do the rounding.
10

This should help... http://www.csharp-examples.net/string-format-int/

So you can use this

string.Format("{0:0000000000.00}", 15.25); // "0000000015.25"

4 Comments

I thought this, too, but re-read the question. The digits to the right of the decimal point should vary and not always be exactly two.
@Yuck That's not how I understand it I need to always display this amount with 10 numbers on the left of the decimal and two after.... it will not work with numbers bigger than 9999999999 though, because then he'll has 11 numbers in front :)
Note that ToString is more efficient than string.Format. In other words, assuming d is a decimal variable, d.ToString("0000000000.00") is more efficient than string.Format("{0:0000000000.00}", d)
Still, if he doesn't need the two on the right he just swaps that format out. This is a viable answer depending on what the OP wants.
2

yourDecimalVariable.ToString("0000000000.00") should do the trick.

Comments

1

If anyone need to have round up while formatting a string, since C# 6.0 you can format a interpolated string as below:

Console.WriteLine($"{value:f2}".PadLeft(13, '0')); 

Where f2 means fixed point with 2 decimal places, then padding '0' to the left.

And the 13 means 10 digits in integral plus 2 decimal places plus the ., thus 13 in total length.

Output:

1245.678f| 0000001245.68 245.567f | 0000000245.57 11245.00f| 0000011245.00 

References:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.