In database I have a PRICE field type of float with value 54342.76 and I want to display it on gridview as 54,342.76. How can format this values?
Try
float f = 54342.76F;
string s = f.ToString("0,0.000", CultureInfo.InvariantCulture);
Console.WriteLine(s);
You could use c specifier instead, however it prints currency sign also.
Use CultureInfo.InvariantCulture as in some localizations , thousands separator may be missing.
Also read Decimal.ToString Method, Standard Numeric Format Strings, Custom Numeric Format Strings
this is what I use:
x.ToString("c")
String.Format("{0:n}", 54342.76F)
The N method is a good solution since it should respect the user's locale while others like:
String.Format("{0:#,###,###.##}", 54342.76F)
Could bypass current culture in some situations. Use {0:n0} instead of {0:n} if you want to display the number without decimals.
In the past I have used this: http://www.codeproject.com/Articles/11531/Money-DataType
It formats money perfectly when used in a DataGridView column.
Related
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 have several strings that I need to convert to float. When I try to do so, using System.Convert.ToSingle(MyString), I always get a FormatException.
I have tried even creating strings like "12.123", to make sure the numbers are okay, but again I got the exception. My question is, what is the correct format then? In what format should the number in string be?
Example of one of many strings I will convert: 50.105128
It could be down to your system's culture which may be set to using a , as the separator. Setting the format to InvariantCulture will use a . for the separator.
Convert.ToSingle("12.123", CultureInfo.InvariantCulture)
It depends on culture, but you can use invariant in this way:
Convert.ToSingle("0", System.Globalization.CultureInfo.InvariantCulture);
Convert.ToSingle is culture-sensitive. In culture installed on your machine, decimal separator might be different from comma, and number may look like 50,105128
Use this overload instead, which allows to specify culture:
public static float ToSingle(
Object value,
IFormatProvider provider
)
I have textbox that accept numbers. Those numbers will be saved in database.
When I enter number like 2,35 and convert to float and send to database I get error because database accept only number with dot, e.g. 2.35
float num = float.Parse(textBox1.Text);
num is still 2,25
How to manage that? I've tried with CultureInfo.InvariantCulture but I never get what I want
You can try the following:
float.Parse(textBox1.Text.Trim(), CultureInfo.InvariantCulture.NumberFormat);
I hope this would've solved the issue.
The easiest way is to replace ',' with '.' in like:
float num = float.Parse(textBox1.Text);
string stringValue = num.ToString().Replace(',', '.');
Then send "stringValue" to database.
I hope that helps you.
use this:
CultureInfo.CreateSpecificCulture("en-US");
I have same problem back then and it solved by code above
num is 2,25 because it's shown to you in your culture. It will be passed correctly to the database, provided you use the usual mechanisms (i.e. prepared statements with parameters). If you insist on manually gluing together SQL, then by all means use InvariantCulture to format the number, but generally, please don't.
This is a common globalization issue. What you have to define is a single culture in which to store the data itself, since you are storing it as a string value. Then, do ALL your data input and handling using that culture. In our code, we have several blocks that look similar to this in order to handle multi-cultural math and data display:
//save current culture and set to english
CultureInfo current = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
//Do Math and Data things
//restore original culture
System.Threading.Thread.CurrentThread.CurrentCulture = current;
This way you can make sure that all the data is handled and stored the same way, regardless of the culture being use to generate or display the data.
Edit
To do the data save, and converting the number to a string, you would do things exactly the same way. While you have the current threads CultureInfo setting as "en-US", the .ToString() methods from all the numbers will use "." instead of "," for the decimal point. The other way to do it is specify a format provider when calling .ToString().
decimalNumber.ToString(new CultureInfo("en-US"));
This specifies that when you convert the number to a string, use the NumberFormat from the provided culture.
I have some prices in my DB which are stored as data type money and have the following code:
result.RangeMinimum = (decimal)ad.RangeMinimum;
result.RangeMaximum = (decimal)ad.RangeMaximum;
The output is:
38000
and
42000
Ideally, what I want is something [exactly] like this:
38, 000.00
and
42, 000.00
How can I achieve this? I mean, is there already an existing class out there that's built into the .NET framework or something?
What you want to achieve can be done through custom numeric format, i.e., for the
ToString() method or the String.Format() method
MDSN Custom Numeric Format
As you specified "exactly" and have a space after the coma it seems standard numeric formats will not work. You can easily customize your own format using String.Format.
Decimal number = 38000.01m;
string formatted = string.Format(CultureInfo.GetCultureInfo("en-US"), "{0:#, ###.00}", number);
// formatted now contains "38, 000.01"
Output is: 38, 000.01
Please always remember cultureinfo so us non-US citizens can enjoy apps. :)
Information on formatting with Custom Numberic Format can be found on MSDN.
Note the 00's at the end, they force two digits. Depending on your use you may or may not want this behavour. Replace with ## if required. Also if you use this in a loop don't to a culture lookup on every call to string.Format.
You can format it like
string.Format("{0:#,#.##}", decimalValue)
string currencyString = result.RangeMinimum.ToString("C", CultureInfo.CurrentCulture);
Try this
result.ToString("N");
using CultureInfo.InvariantCulture u can define your own format
Try
decimal ad.RangeMinimum = Decimal.Parse(result.RangeMinimum.ToString("#0.00"));
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.