Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Request QueryString to Decimal

I can not convert query string to decimal. In this example, when I control Request.QueryString["Amount"] value, It is 32.52 After the below code works, The Amount values is 3252M like that. How can I easily do this?

decimal Amount= 0;
if (Request.QueryString["Amount"] != null)
     Amount = Convert.ToDecimal(Request.QueryString["Amount"]);
like image 752
baros Avatar asked Jul 23 '26 21:07

baros


1 Answers

Convert.ToDecimal uses your current culture settings by default.

I strongly suspect your CurrentCulture's NumberDecimalSeparator property is not ., but NumberGroupSeparator property is .

That's why your program thinks this is a thousands separator, not decimal separator and it parses as a 3252, not 32.52.

As a solution you can use a culture which have . as a NumberDecimalSeparator like InvariantCulture, or you can .Clone your current culture and set it's NumberDecimalSeparator to . 1

Amount = Convert.ToDecimal(Request.QueryString["Amount"], CultureInfo.InvariantCulture);

or

var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ".";
culture.NumberFormat.NumberGroupSeparator = ",";
Amount = Convert.ToDecimal("32.52", culture);

1: If your current culture's thousands separator is not . already. Otherwise, you need to change it as well. Both property can't have the same values for any culture

like image 130
Soner Gönül Avatar answered Jul 26 '26 13:07

Soner Gönül