7
votes

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 :)

2
Just out of curiosity, can it parse "123,95" ? - Vlad
Jon Skeet just saved your question from being closed - Force444
just tried it and it worked... was along time since i coded. so was looking online for how decimals worked and there were '.' everywhere. - Pepps
@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). - p.s.w.g

2 Answers

19
votes

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); 
1
votes

Use this code -

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

It worked for me.