11

Visual studio wont convert my string to decimal

Error: Input string was not in a correct format.

Code:

string test = "123.95";
decimal test1 = decimal.parse(test); // string being an int "123" doesnt cause this

also Convert.toDecimal(test); does just the same.

EDIT: Thanks for the answers, I was looking online for how decimals worked and everyone were using '.' and not ','. Sorry about how incredibly stupid I and this post is. And thanks again for the answeres :)

4
  • Just out of curiosity, can it parse "123,95" ? Commented Mar 25, 2014 at 19:24
  • 2
    Jon Skeet just saved your question from being closed Commented Mar 25, 2014 at 19:25
  • just tried it and it worked... was along time since i coded. so was looking online for how decimals worked and there were '.' everywhere. Commented Mar 25, 2014 at 19:27
  • @Pepps decimal literals are expressed as 123.95 almost universally in programming languages. However, the string representation of that decimal varies widely from one region to another around the earth. .NET is trying to be nice and read in decimal the way you would most naturally write them (accordion to the locale settings on your computer). Commented Mar 25, 2014 at 19:31

2 Answers 2

28

It's likely your current culture doesn't use . as a decimal separator. Try specifying the invariant culture when you parse the string:

using System.Globalization;

...

string test = "123.95";
decimal test1 = decimal.Parse(test, CultureInfo.InvariantCulture); 

Alternatively, you could specify a culture that uses the specific format you want:

string test = "123.95";
var culture = new CultureInfo("en-US");
decimal test1 = decimal.Parse(test, culture); 
Sign up to request clarification or add additional context in comments.

Comments

1

Use this code -

var test1 = "123.95";
decimal result;
decimal.TryParse(test1, out result);

It worked for me.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.