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

Sunday, August 7, 2022

[FIXED] How do I parse a decimal number from a string to an integer in C#?

 August 07, 2022     asp.net, c#, decimal, decimal-point, string     No comments   

Issue

I want to convert a decimal string to an integer but I keep getting the following error:

System.FormatException: Input string was not in a correct format.

var myString = "18.7";
var myInteger = Int32.Parse(myString); //flaging an error here
Console.WriteLine(myInteger) //desired result = 18

Solution

You should parse it to a double type and cast it to an integer

var myString = "18.7";
var myInteger = (int)Convert.ToDouble(myString); 
Console.WriteLine(myInteger) //desired result = 18

The conversion will be like this

  • "18.7" (a string value) to 18.7 (a double value)
  • 18.7 (a double type) to 18 (an integer type - the decimal part gets removed)

In some cases, your strings may be like 18,7 which is relied on CultureInfo for conversion. That makes 18.7 unformattable.

As for culture independency, you can convert it like below

var myString = "18.7";
var myInteger = (int)Convert.ToDouble(myString,CultureInfo.InvariantCulture.NumberFormat); 
Console.WriteLine(myInteger) //desired result = 18


Answered By - Nick Vu
Answer Checked By - Katrina (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