PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] Why Convert.ToInt32 or Int32.Parse do not work for me?

 July 21, 2022     .net, c#, integer     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing