Reputation: 251
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"]);
Upvotes: 3
Views: 2605
Reputation: 98810
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
Upvotes: 5
Reputation: 771
I think you are having problems with the Culture as stated in the rpevious answer. You may want to try using different cultures:
RetVal = decimal.Parse(Request.QueryString["Amount"], CultureInfo.CurrentCulture);
Then I would try:
RetVal = decimal.Parse(Request.QueryString["Amount"], CultureInfo.InvariantCulture);
Upvotes: 0