Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello folks,

here's a quick question: How can I convert this string "123,45" to this int 12345?
But the same method should convert "123,445" to this int 12345 or "123,40" to this int 12340.
I hope you can see the system behind it. I also don't want to use float, double or decimals in that method as I want high precision on very big numbers (for example this string "123456789,0123" to 12345678901)
Posted
Comments
ShivKrSingh 9-Sep-13 9:35am    
this may give you overflow error. because it you may not have idea of full number range. It can be greater then the size of int32 like your example 123456789,0123 and you want to convert it 1234567890123 this number is greater then Int32 range. You should confirm your digits before changing it into Int32. It is better to use Number(Max digit you want before decimal, decimal places) in sql server and use double in front end. you can use round off if you want in this Case. but not in your condition.

First of all, this operation is called parsing. This is what really happens when you try to interpret a string as a representation of a number.

This is how:
C#
string input = //...
int value = int.Parse(input, System.Globalization.NumberStyles.AllowThousands);

or
C#
string input = //...
int value;
bool success = int.TryParse(input, System.Globalization.NumberStyles.AllowThousands, null, out value);


Please see:
http://msdn.microsoft.com/en-us/library/c09yxbyt.aspx[^],
http://msdn.microsoft.com/en-us/library/zf50za27.aspx[^],
http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles.aspx[^].

First variant may throw exception, so you may need to handle it and let a user a change to input correct value. In the second sample, you can do the same without using any exception, but you need to check up the result of the call.

The null value for format provider means using the current culture. In case of ',' as a thousands or hundreds separator, this is important, because some other cultures use '.' (or something else), to this format is culture-dependent, so it won't work in all cases. In you always want ',', you should rather specify some fixed culture, such as new System.Globalization.CultureInfo("en-US", false); please see:
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx[^].

—SA
 
Share this answer
 
Comments
Herbisaurus 9-Sep-13 9:58am    
*****
Sergey Alexandrovich Kryukov 9-Sep-13 10:00am    
Thank you.
—SA
you can use Convert.ToInt32, it takes special number chars like '+' '-' ',' etc
C#
// This will parse +2,147,483,647 as 2147483647 
Convert.ToInt32(input);


If you have a funny string input and you want to remove all the non-numeric chars, you can use Regex:
C#
// This regex will remove any char that is not a number or '+' or '-'
Regex rgx = new Regex("[0-9+-]");
str = rgx.Replace(str, "");

Best,
H
 
Share this answer
 
v3
C#
private static int ToInt(string t)
        {
            string[] spl = t.Split(new char[]{',', '.'});
            int f = Convert.ToInt32(spl[0]) * 100;
            double d = Convert.ToDouble("0," + spl[1]);
            d = Math.Round(d, 2);
            if (d >= 1.0d)
            {
                f += 100;
                d -= 1.0d;
            }
            f += Convert.ToInt32(d * 100);
            return f;
        }

This oe should work.
 
Share this answer
 
Comments
Estys 9-Sep-13 10:09am    
It won't work if the result of your input string could be larger than 2,147,483,647 (the "," [comma] is used here as a thousand-seperator). The max value of int32 is 2**31-1. You could as well use the much simpler methods offered by the others if the range is sufficient.
string s="1234,4578,24569";
string a=s.Replace(",","");
int b=int.parse(a);
 
Share this answer
 
You mean you always want 2 numbers after comma?

C#
string stringValue = "123.45";
int integerValue;
double value;
if (double.TryParse(stringValue, out value)) {
   value = Math.Round(value, 2);
   integerValue = (int)(value * 100);
}
else {
   integerValue = 0;
}
 
Share this answer
 
v2
Comments
IDominator 9-Sep-13 9:42am    
Yes I want the 2 decimals after comma to be also converted in the integer.
This solution works for small numbers. But with increasing digits in the string value, the precision of parsing it to a double gets worse. Thats the reason I don't want to use a double in this method.
I had an idea to split the string value into to strings. The one before the comma and the other after. So I can directly convert the string value to Int and multiplying it by 100 and the other string I convert to a double and round it with Math.Round. The problem with this method is obvious: I have this string "9,99" and I want 1000 but with this method I get 900
phil.o 9-Sep-13 9:45am    
And did you try with decimal instead of double? decimals have a more narrow range but a better precision.
Sergey Alexandrovich Kryukov 9-Sep-13 9:49am    
This is your who tried double. This is pointless.
OP explicitly told you: " I also don't want to use float, double or decimals...", which is perfectly right.
—SA
Sergey Alexandrovich Kryukov 9-Sep-13 9:48am    
This is all wrong. Please see my solution.
—SA
Sergey Alexandrovich Kryukov 9-Sep-13 9:46am    
No, OP meant that it may be the case. To my surprise, it is allowed for integers, at least in "en-US" culture. First of all, it won't work for int without System.Globalization.NumberStyles.AllowThousands. Check it up and you will see. Please see my answer.

And your solution with double is simply incorrect. OP is right: you need to use int and only int.

Also, your assumption that invalid input should mean 0 is not based on anything. At least you should have commented on that. It would be saver to say, it's up to the inquirer...

—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900