Issue
It should be a simple code:
string qty = "211.0000";
Console.WriteLine(Int32.Parse(qty));
I tried to use Convert.ToInt32
or Int32.Parse
, but they all throw an error:
Error(s):
Exception in user code:
System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at Rextester.Program.Main(String[] args)
Did I make any errors to define a string and give a value? I have tried use string
or String
to define the variable. It works if I use Console.WriteLine(Convert.ToInt32("211.0000"))
.
BTW I was testing in http://rextester.com/
Solution
When working with floating point values (which have explicit decimal separator .
) you should use decimal
or double
:
using System.Globalization;
...
string qty = "211.0000";
// be careful: different cultures have different decimal separators
decimal result = decimal.Parse(qty, CultureInfo.InvariantCulture);
or
double result = double.Parse(qty, CultureInfo.InvariantCulture);
having got floating point representation you can round it up to integer
int value = (int) (result > 0 ? result + 0.5 : result - 0.5);
or
int value = (int) (Math.Round(result));
Answered By - Dmitry Bychenko Answer Checked By - Clifford M. (PHPFixing Volunteer)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.