user3284126
user3284126

Reputation: 55

Convert String With Zeros To Decimal

I have a string like this: "000123".

I want to know how to convert this string to decimal but keep the leading zeros. I have used Convert.ToDecimal(), Decimal.TryParse & Decimal.Parse. But all of those methods keep removing the leading zeros. They give me an output: 123. I want the decimal returning 000123. Is that possible ?

Upvotes: 0

Views: 2315

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29036

So you need to store 000123 in a decimal variable, First of all it is not possible since 000123 is not a Real Number. we can store only Real numbers within the range from -79,228,162,514,264,337,593,543,950,335 to +79,228,162,514,264,337,593,543,950,335 in a decimal variable. No worries you can achieve the target, decimal.Parse() to get the value(123) from the input(as you already did) and process the calculations with that value. and use .ToString("000000") whenever you wanted to display it as 000123

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502206

No, it's not. System.Decimal maintains trailing zeroes (since .NET 1.1) but not leading zeroes. So this works:

decimal d1 = 1.00m;
Console.WriteLine(d1); // 1.00
decimal d2 = 1.000m;
Console.WriteLine(d2); // 1.000

... but your leading zeroes version won't.

If you're actually just trying to format with "at least 6 digits before the decimal point" though, that's easier:

string text = d.ToString("000000.#");

(That will lose information about the number of trailing zeroes, mind you - I'm not sure how to do both easily.)

Upvotes: 2

Related Questions