I get from a webservice the following strings:
12.95
or
1,200.99
Is there an option to convert these values to the following values without manipulating the string?
12,95
or
1200,99
I tried it with some Culture options but didn't get it right...
EDIT
I tried this:
//return string.Format( "{0:f2}", Convert.ToDecimal( price ) );
//return string.Format(CultureInfo.GetCultureInfo("de-de"), "{0:0}", price);
NumberFormatInfo format = new System.Globalization.NumberFormatInfo();
format.CurrencyDecimalDigits = 2;
format.CurrencyDecimalSeparator = ",";
format.CurrencyGroupSeparator = "";
return decimal.Parse(price).ToString(format);
var input = "1,200.99";
//Convert to decimal using US culture (or other culture using . as decimal separator)
decimal value = decimal.Parse(input, CultureInfo.GetCultureInfo("en-US"));
//Convert to string using DE culture (or other culture using , as decimal separator)
string output = value.ToString(CultureInfo.GetCultureInfo("de-DE"));
Console.WriteLine(output); //1200,99
What about something like this:
double number;
double.TryParse("1,200.99", NumberStyles.Any, CultureInfo.CreateSpecificCulture("en-US"), out number);
var formattedNumber = number.ToString(CultureInfo.CreateSpecificCulture("de-DE"));
Then return or write out formattedNumber (whatever you need to do).
Yes and no. First, what you have is a string, and so you cannot change the formatting of it as you're attempting to. However, to achieve what you would like, you can parse the string into a decimal value and then use the formatting options for decimals to display it in any reasonable way.
You may try for something like this:
String.Format("{0:#,###0}", 0);
or may be like this:
string str = yourNumber.Remove(",").Replace(".",",");
Close enough tronc,
Try this snippet:
String curStr = "12.95";
Decimal decVal;
var valid = Decimal.TryParse(curStr, out decVal);
if (!valid) throw new Exception("Invalid format.");
String newFormat = decVal.ToString("C", System.Globalization.CultureInfo.CreateSpecificCulture("de-DE"));
Within the toString(...) call, you can append a number after 'C' to specify how many decimal places should follow. E.g "C3".
Related
I have a question. how to changes "15.49" in string array to int value in c#?
Based on your comment, your culture uses "," as decimal separator, instead of ".". You could use overload of decimal.Parse to use custom culture format. Since you want to ignore the decimal part, you can use Int32.Convert to fetch the int part.
var stringValue = "15,49";
var culture = (CultureInfo)CultureInfo.InvariantCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ",";
culture.NumberFormat.NumberDecimalSeparator = ",";
var result = Convert.ToInt32( decimal.Parse(stringValue, culture));
This would give your the required result
(int)decimal.Parse("15.49"); - if string null, parse return exception (maybe its what you want)
(int)Convert.ToDecimal("15.49"); if string null, convert return 0
If i am not wrong you want to convert string "15.49" into int ??? If yes then you can use this code Convert.toInt32("15.49");
My code:
public decimal SetHourRate(string hourrate)
{
var value = decimal.Parse(hourrate, NumberStyles.Currency, CultureInfo.CurrentCulture.NumberFormat);
return value;
}
In parameter:
string hourrate = "800.00"
My problem:
Right now my output is like var value = 80000? I want it to be like the string I put in. I'm from Sweden and we have a dot instead of comma to separate the decimals in currency. It must work even if the string look like this string hourrate = "1050.67".
It's ok if the output will be like var value = "800,00" or var value ="1050,67"(comma instead of dot.)
It is returning the 80000 because the . in the swedish is the GroupSeparator. The , is the decimal separator.
You are passing a string like 800.00 so, . will be used as group separator. That is the reason you are getting this value.
You could force the decimal separator to be . chaging the a formater (CultureInfo), for sample:
public decimal SetHourRate(string hourrate)
{
var swedishCulture = new CultureInfo("sv-SE");
swedishCulture.NumberFormat.NumberDecimalSeparator = ".";
var value = decimal.Parse(hourrate, NumberStyles.Currency, swedishCulture);
return value;
}
You have to use CultureInfo to specify what formatting to use when parsing.
CultureInfo culture = new CultureInfo("sv-SE");
culture.NumberFormat.NumberDecimalSeparator = ".";
decimal value;
if (decimal.TryParse(hourrate, NumberStyles.Currency, culture, out value))
{
// Do what you want with value if successfully parsed
}
else
{
// Failed to parse
}
Make sure you include System.Globalization at the top of your code.
I'm a bit stuck: I am trying to perform an if statement comparing a label.text that originally has a currency string created from .ToString("C");
and a decimal. I have tried converting the label to decimal since I'm going to be comparing it to a decimal but it keeps triggering an exception:
Input string was not in a correct format.
here is my current code:
if(Convert.ToDecimal(SomeLabel.Text) > 1000.00m) { //DO SOMETHING }
//SomeLabel.Text has a value of $1000.00
//SomeLabel.Text has a value of $1000.00
The dollar sign is the reason for the issue. Yoa are probably using a different currency symbol. You can force it with decimal.Parse/decimal.TryParse(which handles invalid input):
string input = "$1000.00";
decimal decimalValue;
if(decimal.TryParse(input, out decimalValue))
{
// using current CurrencySymbol, same as Convert.ToDecimal
Console.WriteLine("Converted successfully: " + decimalValue);
}
else
{
var usCulture = new CultureInfo("en-US");
if (decimal.TryParse(input, NumberStyles.Currency, usCulture, out decimalValue))
{
// using dollar sign as CurrencySymbol
Console.WriteLine("Converted successfully with CultureInfo(en-US): " + decimalValue);
}
else
{
Console.WriteLine("Could not be parsed to decimal");
}
}
Output:
Converted successfully with CultureInfo(en-US): 1000.00
It's worth noting that NumberFormatInfo.InvariantInfo.CurrencySymbol does not return the dollar sign(what i thought) but ¤.
Convert.ToDecimal uses decimal.Parse explicitly this method uses NumberStyles.Number by default.
This is a composite style which includes AllowDecimalPoint but not AllowCurrencySymbol style even if your CurrentCulture's CurrencySymbol is $ and NumberDecimalSeparator is ..
You can use decimal.parse(String, NumberStyles, IFormatProvider) overlaod that takes these as a parameters like;
string s = "$1000.00";
var d = decimal.Parse(s, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint,
CultureInfo.GetCultureInfo("en-US"));
d will be 1000 after parsing.
As per your example. your string value is $1000.00.
This contains a $ sign that's why the compiler is unable to cast string to decimal.
try removing the unusable character by replace. Or try the method below
Regex digitsOnly = new Regex(#"[0-9.]"); // this regex matches only digits and decimal
string decimalnumberstring = digitsOnly.Replace(SomeLabel.Text, "");// replace all non numbers (except decimal) with empty string
then try to convert the string value like below.
if(Convert.ToDecimal(decimalnumberstring) > 1000.00m) { //DO SOMETHING }
hope it helps....
Take the Dollar Sign off of your text first:
Source: $1000
double result = 0M;
String value = SomeLabel.Text.Substring(1);
if (Double.TryParse(value, out result)) {
//
}
return result;
Try this
if(decimal.Parse(SomeLabel.Text) > 1000.00m)
{
}
Hi all. I have a double number (Ex: 0.000006). I want convert it to string type. But result is "6E-06". I dont want it, i want 0.000006".Thanks you so much
double a = 0.000006;
string resultString = a.toString();
I don't know many number after "." character
It's simple that if you want to show a number as exactly as what it looks, we can cast it to decimal and use the default ToString() like this:
var s = ((decimal)yourNumber).ToString();
//if yourNumber = 0.00000000000000000000000006
//just append the M after it:
var s = (0.00000000000000000000000006M).ToString();
Please check this article and find the format which suits your needs: http://www.csharp-examples.net/string-format-double/
Looks like this one is good enough:
String.Format("{0:0.00}", 123.4567);
Use String.Format() with the format specifier.
double a = 0.000006;
string formatted = String.Format("{0:F6}", a);
Try with the Roundtrip 'R' format specifier:
double a = 0.000006;
string resultString = a.ToString("R");
Double Rate_USD = Convert.ToDouble(txtRateUsd.Text);
string Rate_USD = txtRateUsd.Text;
I am trying to convert string to India Money format like if input is "1234567" then output should come as "12,34,567"
I have written following code but its not giving the expected output.
CultureInfo hindi = new CultureInfo("hi-IN");
string text = string.Format(hindi, "{0:c}", fare);
return text;
can anyone tell me how to do this?
If fare is any of int, long, decimal, float or double then I get the expected output of:
₹ 12,34,567.00.
I suspect your fare is actually a string; strings are not formatted by string.Format: they are already a string: there is no value to format. So: parse it first (using whatever is appropriate, maybe an invariant decimal parse), then format the parsed value; for example:
// here we assume that `fare` is actually a `string`
string fare = "1234567";
decimal parsed = decimal.Parse(fare, CultureInfo.InvariantCulture);
CultureInfo hindi = new CultureInfo("hi-IN");
string text = string.Format(hindi, "{0:c}", parsed);
Edit re comments; to get just the formatted value without the currency symbol or decimal portion:
string text = string.Format(hindi, "{0:#,#}", value);
String.Format("0:C0") for no decimal places.
As per my comment above you can achieve what you desire by cloning a numberformatinfo and set the currency symbol property to empty string
Example can be found here - look down the bottom of the page
EDIT: Here is the above linked post formatted for your question:
var cultureInfo = new CultureInfo("hi-IN")
var numberFormatInfo = (NumberFormatInfo)cultureInfo.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "";
var price = 1234567;
var formattedPrice = price.ToString("0:C0", numberFormatInfo); // Output: "12,34,567"
Try this
int myvalue = 123456789;
Console.WriteLine(myvalue.ToString("#,#.##", CultureInfo.CreateSpecificCulture("hi-IN")));//output;- 12,34,56,789
If you want to show in Razor view file, then use,
#String.Format(new System.Globalization.CultureInfo("hi-IN"), "{0:c}", decimal.Parse("12345678", System.Globalization.CultureInfo.InvariantCulture))
// Output: ₹ 1,23,45,678.00