Reputation: 10815
I have this value in a string
string FinalValue=" 0XXXXXXXXX";
which i need to fetch in integer value.
But when i convert it like below
custNUmber = int.Parse(FinalValue);
it says value was either too large or too small for an int32. c#
and when i use long it skips the first digit 0.
Upvotes: 1
Views: 384
Reputation: 186823
Maths says that 07894204661 == 7894204661
that's why resulting long
is always 7894204661; if you want to restore leading zeros when converting long
back to String
(e.g. in order to show it in a TextBox, print out to Console etc.) you can use formatting:
String FinalValue=" 07894204661";
long custNUmber = long.Parse(FinalValue.Trim());
// 11 digits wanted; "07894204661" is the outcome
String value = custNUmber.ToString("D11");
P.S. int.MaxValue == 2147483647
only; that is the cause of the exception when you try to convert "07894204661" into int
.
Upvotes: 6
Reputation: 460268
A leading zero is not part of an integer at all. Actually 0123==123
yields true.
So you could convert it to long first to handle the case that it's a numeric value that is simply to large (f.e. for logging purposes):
int custNUmber;
long l;
if(long.TryParse(FinalValue, out l))
{
if(l < int.MinValue || l > int.MaxValue)
{
// log
}
else
{
custNUmber = (int)l;
}
}
else
{
// not a number
}
Upvotes: 2
Reputation: 4348
using long is the right thing to do. The zero isn't part of the number so it's supposed to skip it. I'd worry about the leading space. You might need to trim that off before parsing it.
custNUmber = long.Parse(FinalValue.trim());
Upvotes: 0