Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Won't convert string to decimal c# (Input string was not in a correct format.)

Tags:

string

c#

decimal

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

like image 688
Pepps Avatar asked Mar 25 '14 19:03

Pepps


2 Answers

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); 
like image 162
p.s.w.g Avatar answered Nov 15 '22 21:11

p.s.w.g


Use this code -

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

It worked for me.

like image 39
arpitbakshi Avatar answered Nov 15 '22 23:11

arpitbakshi