Convert float string to int c#

Converting a string to a integer seems to be trivial. But there could be endless of formats and styles on the string so it’s not always that easy that it’s seems.

If you have a string like “629.00” and want convert it to a int like 629. You can do like this:

int.Parse( ("629.00").Replace('.',','), NumberStyles.Float)

But if you try the code above with for example value “3187.50” instead you get this error message:

vid System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
vid System.Int32.Parse(String s, NumberStyles style)
vid System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
vid System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
vid Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
vid System.Threading.ThreadHelper.ThreadStart_Context(Object state)
vid System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

Then you need to do like:

(int) double.Parse("3187.50".Replace('.', ','), NumberStyles.Float)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.