C
C#14mo ago
TheOneAndOnly

❔ How would one convert string to int?

I have a string "1.65" for example which I would want to convert to a int with the value 1.65
13 Replies
Angius
Angius14mo ago
That isn't an int But you would use T.Parse() or better yet, T.TryParse() where T is the type you want to parse into So in your case, some sort of a decimal type double, float, decimal, etc
TheOneAndOnly
TheOneAndOnlyOP14mo ago
Oo yeah no not a int indeed But needed to no how to Parse with C#
MODiX
MODiX14mo ago
Angius
REPL Result: Success
var str = "1.65";
if (double.TryParse(str, out var num))
{
Console.WriteLine($"The value is {num}");
}
else
{
Console.WriteLine("Not a valid number");
}
var str = "1.65";
if (double.TryParse(str, out var num))
{
Console.WriteLine($"The value is {num}");
}
else
{
Console.WriteLine("Not a valid number");
}
Console Output
The value is 1.65
The value is 1.65
Compile: 662.527ms | Execution: 49.124ms | React with ❌ to remove this embed.
TheOneAndOnly
TheOneAndOnlyOP14mo ago
Thanks!
arion
arion14mo ago
if you want that double (or float if you want) to be int you can use Convert or Cast Just a heads up, Convert and Cast may yield different results
Angius
Angius14mo ago
You will lose the decimal part though It'd be best to round it first, then cast to int
arion
arion14mo ago
Yes, Convert will round it up, cast will round it down
Angius
Angius14mo ago
That way you have control over whether to round it, floor it, or ceiling it
TheOneAndOnly
TheOneAndOnlyOP14mo ago
Its representive of a percentage, so the only thing I would maybe have to do is *100
MODiX
MODiX14mo ago
arion
REPL Result: Success
var x = "1.69";
var ourFloat = float.Parse(x);
var roundedUp = Convert.ToInt32(ourFloat);
var roundedDown = (int)ourFloat;

Console.WriteLine($"Converted: {roundedUp}, Casted: {roundedDown}");
var x = "1.69";
var ourFloat = float.Parse(x);
var roundedUp = Convert.ToInt32(ourFloat);
var roundedDown = (int)ourFloat;

Console.WriteLine($"Converted: {roundedUp}, Casted: {roundedDown}");
Console Output
Converted: 2, Casted: 1
Converted: 2, Casted: 1
Compile: 723.563ms | Execution: 53.269ms | React with ❌ to remove this embed.
arion
arion14mo ago
That might be the best nod
TheOneAndOnly
TheOneAndOnlyOP14mo ago
Hehe 69
Accord
Accord14mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server