C# Padding Amount With Zeros
Asked Answered
G

3

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?

Gregoriogregorius answered 6/3, 2012 at 16:30 Comment(0)
R
31

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.

Ricardo answered 6/3, 2012 at 16:34 Comment(1)
This will do the rounding.Pabulum
O
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"

Offen answered 6/3, 2012 at 16:32 Comment(4)
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.Cauvery
@Cauvery 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 :)Offen
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)Distillate
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.Ricardo
S
2

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

Suited answered 6/3, 2012 at 16:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.