Please observe following simple code. Why the variable inVarient prints without decimal point. I want decimal point, how to achieve it?
decimal actualVal = 1247315.93m;
string inSwedish = actualVal.ToString(CultureInfo.CreateSpecificCulture("sv-SE"));
decimal inVarient = decimal.Parse(inSwedish, CultureInfo.InvariantCulture);
Console.WriteLine(inSwedish); //prints 1247315,93 (as intended)
Console.WriteLine(inVarient); //prints 124731593 (I need 1247315.93)
Console.Read();
This is because you're trying to parse a string that represents a decimal formatted with the Swedish culture but you're trying to parse it with the invariant culture, which won't treat a comma as a decimal point. You need something like this:
decimal actualVal = 1247315.93m;
var culture = CultureInfo.CreateSpecificCulture("sv-SE");
string inSwedish = actualVal.ToString(culture));
decimal invariant = decimal.Parse(inSwedish, culture);
Console.WriteLine(inSwedish);
Console.WriteLine(invariant.ToString(CultureInfo.InvariantCulture));
Console.Read();
Swedish culture uses , as a decimal separator, the invariant culture uses ., so when it parses a string using the comma as a separator it just ignores it.
The reason why your decimal point disappears here is because in the invariant culture, a comma is a thousands separator, not a decimal separator. Thus, it assumes it can safely ignore commas when parsing a numeric text.
If you go back and forth from a culture to another, this kind of thing is to be expected.
I don't know what your real context is but if you want to recover the numeric as it originally was before it was made a string, you must either use consistent formatters throughout your code or not storing decimals into string variables only to parse them back to decimal again.
If there's no need to serialize anything the latter is the way to go.
Related
in my website i need to read data from a XML, and some of these datas are decimal values.
Sometimes the value comes correct: 1 or 72,59and sometimes the value comes like 1.0000 or 72,590000, how is the best way to convert it to the right format:
ps: I need a string value.
Thanks!
What format are you wanting them to go to, specifically? How many decimals, etc?
If you want always 2 decimals, try a standard numeric formatting such as:
decimal value = 123.456;
Console.WriteLine("Your account balance is {0:F}.", value);
See this MSDN example for other common numeric formatting techniques.
You write that you tried
string.Format("{0:F}","1.00000");
The problem with this is that you're passing a string into the function. Numeric formatting only works on numeric data types. Convert the value to a decimal first and then format it.
Try this
public string ReformatDecimalString(string input)
{
const string formatString = //something
var decimalValue = decimal.Parse(input);
return decimalValue.ToString(formatString);
}
When you are formatting a single numeric value, it's slightly more efficient to use x.ToString(formatString) than string.Format(formatString, x). But note that the specific format string will be different in the two cases.
If your input data has decimal points (not commas) and your computer's culture uses decimal commas, you ought to be able to parse the value correctly by using CultureInfo.InvariantCulture:
var decimalValue = decimal.Parse(input, CultureInfo.InvariantCulture);
If I'm reading your answer correctly, you're trying to convert Integer values you pull from an XML file into string values without trailing zeroes ("ps: I need a string value.")
this code:
decimal test = 20.000000m
test.ToString("G29");
might do what you want
I have a string totalPRice which holds a value like this 1147,5
I want two things.
1)round the value so that there is always two digits after ,
2)Implement thousands separator in this string, So that final out put will be some thing like this 1.147,50
I have tried some thing like this
String.Format("{0:0.00}", totalPRice)
It does my first requirement correctly by producing an output 1147,50.
But I am way behind in my second requirement. Can any one tell me how I can achieve this?
Note: In danish culture . stands for , and , stands for .
You can refer to Standard Numeric Format Strings and use
string.Format("{0:N2}", 1234.56)
You may also specify the culture manually, if danish is not your default culture:
var danishCulture = CultureInfo.CreateSpecificCulture("da-DK");
string.Format(danishCulture, "{0:N2}", 1234.56);
see MSDN Reference for CultureInfo
You should create a culture-specific CultureInfo object and use it when converting the number into a string. Also, you can set the default culture for your whole program.
Then, your code will look like this:
// create Dennmark-specific culture settings
CultureInfo danishCulture = new CultureInfo("da");
// format the number so that correct Danish decimal and group separators are used
decimal totalPrice = 1234.5m;
Console.WriteLine(totalPrice.ToString("#,###.##", danishCulture));
Note that . and , in the formatting string are specified opposit as you want. This is because they identify decimal and group separators, and are replaced with the correct culture specific-ones.
Try this:
String.Format("{0:N2}", totalPRice)
Another possibility is to use the ToString(string format) overload.
totalPRice.ToString("N2");
If this is a currency value (money!), then it's better to use the current format specifier 'C' or 'c':
string.Format("{0:C}", 1234.56)
Normally I don't write the number of decimal digits since it comes from the international configuration.
You may way to use a different colture specifier if you don't want to use the default one.
var colture = CultureInfo.CreateSpecificCulture("§§§§§");
string.Format(culture, "{0:C}", 1234.56);
where §§§§§ is the string that identifies the desired colture.
Try this for Price format. Put it under template field instead of BoundField.
<%#(decimal.Parse(Eval("YourDataField").ToString())).ToString("N2")%>
I need to write decimal value to ms access database, but i have a problem with conversion values to decimal in different cultures. Have a values from file, which separates by commma. I try:
public decimal CSingleCulture (string str)
{
string sep = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
string s = str.Replace(",", sep);
return decimal.Parse(s);
}
if NumberDecimalSeparator = "." then work is good, but if NumberDecimalSeparator = "," problems begin... decimal.Parse(s) always return vlaues separates by dot. In this situation, when inserted into a database error occurs.
The recommended way to deal with this is to store the value as a number rather than a string. Both in the database and in your program. When you do that, your current problem simply never arises.
The only time you deal with numbers in string format is when you display them, or accept user input. In those scenarios you can use the user's culture settings to let them see and use their preferred separator.
Should you ever need to convert between string and number for persistence then you must use culture invariant conversion. This appears to be where you are falling down. I suspect that the file you read has no well-defined format. Make sure that when you read and write the file you use CultureInfo.InvariantCulture. If the file does have a well-defined format that differs from the invariant culture, then use an appropriate specific CultureInfo.
Can't actually understand what is it you're trying to accomplish, and I have to agree with the other answer. But one other thing that's good to know is you can use invariant culture like so:
double.Parse("15.0", CultureInfo.InvariantCulture)
This will always expect dot character to delimit your decimal digits regardless of what is set in current thread's culture.
In Form_load I have
txtAlteFonduri.Text = "5,00";
txtFReparatii.Text = "15,00";
txtFRulment.Text = "20,00";
and in another function I want to parse text as decimal
decimal alteFonduri = Decimal.Parse(txtAlteFonduri.Text);
decimal fondRulment = Decimal.Parse(txtFRulment.Text);
decimal fondRepar = Decimal.Parse(txtFReparatii.Text);
but I have an error in the second line
Input string was not in a correct format.
You need to specifically add the number format. For your examples above, the following should work:
decimal alteFonduri = Decimal.Parse(txtAlteFonduri.Text, CultureInfo.GetCulture("de-DE"));
Otherwise, the system's culture information is used.
You are using a different culture to what decimal.Parse() is expecting (it expects the decimal point '.' but you provide a comma. Using the correct culture should correctly parse the strings, although I can run your code without having any errors...
You can use Decimal.Parse(variable, CultureInfo.GetCultureInfo("Culture-Name"));
You have to use this overload of Decimal.Parse and supply a IFormatProvider matching the culture of your input. You should also consider using one of the Decimal.TryParse methods for better error handling.
I have a nullable float. The internal decimal places can be separated with dot or comma e.g. 1.2 or 1,2. I need this float as a string to compare it to a Regex. If I use the Convert.toString method, the float with the comma is 12 and not 1.2. How can I convert a float to String without loosing the comma or the dot? I alredy tried to convert it with diffrent cultures.
Thanks for your help
A solution for this can be the following:
float? num = 1.2f;
string floatAsString = string.Format("{0:f}", num.Value);
Maybe you need to check if the HasValue property is true before you use the value. For more examples: http://alexonasp.net/samples/stringformatting/
String.Format() function with mask. But can you convert your strings to numbers rather than your numbers to strings, for purposes of the comparison? Does it have to be a regex comparison?
Try:
string s = yourFloat.ToString();
Using the invariant culture is recommended if you want to be sure that your output will be in the correct form, but I'd be surprised if there were a culture which doesn't output a comma or a dot.
I would also suggest not using regular expressions to validate the value of a float.
Are you certain that the textbox allows both "." and "," as a decimal-separator (as opposed to a grouping character, also known as a thousands-separator)?
When you are certain that you only get decimal separators and no grouping characters, replace any "," with a "." before using TryParse with an InvariantCulture to convert the string to a float.
OR use the same culture in the code as on the client side, so both will use the same decimal separators.
As others mentioned, a float doesn't have the concept of various decimal separators.
Ok I solved the problem. I did in my xaml a converter which only allows to enter values with commas as separator, so I dont need any checks if there are only two internal decimal places. Thanks for your help
If it's a WinForm Application, there's a static variable Application.CurrentCulture.NumberFormat.NumberDecimalSeparator.
Depending on it's value you get different results when converting ToString().
Try manipulating this parameter to achieve necessary result.