How to convert string to ToString("#,##0") format - c#

in my application i am update my ui with my label and i want to show the number in #,##0 format.
myClass.getNumberOfFiles return string.
myLabel.Text = myClass.getNumberOfFiles();

Assuming getNumberOfFiles returns a string (which, by its name, it shouldn't) :
myLabel.Text = int.Parse(myClass.getNumberOfFiles()).ToString("#,##0");

I suspect you want the standard "numeric" format specifier, with a precision of 0:
label.Text = GetNumberOfFiles().ToString("N0");
This is after you've fixed your getNumberOfFiles() method to be GetNumberOfFiles() (naming convention) and made it return int or long (a method which is meant to fetch a number should not return a string).
This will use the appropriate grouping for the current culture; if you want a different culture you can specify it as a second argument.

int files;
if (int.TryParse(myClass.getNumberOfFiles(), out files)) {
myLabel.Text = files.ToString("N0");
}
This won't work if you have any formatting in the number already I think. It will work though if on the return of getNumberOfFiles() someone was turning an int into a string. If getNumberOfFiles() is returning a formatted string, you will need to do some different stuff. Below assumes the formatting is in the en-US format coming in and you want to display it in Brazilian Portuguese for example. It is shown in a verbose manner so you know how to plug other cultures in if you need to. If its formatted and doesn't need to change between cultures I don't know why you couldn't just assign the return of getNumberOfFiles() directly to the label's Text property.
int files;
var incomingCulture = CultureInfo.CreateSpecificCulture("en-US");
var outgoingCulture = CultureInfo.CreateSpecificCulture("pt-BR");
if (int.TryParse(myClass.getNumberOfFiles(), NumberStyles.Number, incomingCulture, out files)) {
myLabel.Text = files.ToString("N0", outgoingCulture);
}
That being said I agree with all the others saying it is ridiculous to return a string for an integer. But I know sometimes you don't have the luxury of being able to change it.
I'll also point out that if you use the named format specifiers like "N0", one day a programmer coming behind you will bless you in their heart when they have to globalize your code. This is because every CultureInfo instance has an implementation for each of the named formats, however it is impossible for it to have implementations for custom format specifiers.

Related

Date format different on server

When I execute the code below, I am getting my dates formatted as 04-07-2015 which is as expected what I want.
But when I execute the same code on another server, I am getting date as 7/4/2015. Why?
Here is my code on pageload:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
fillProject();
}
grdData.Visible = false;
TxtIndate.Value = System.DateTime.Now.ToShortDateString();
txtOutDate.Value = System.DateTime.Now.ToShortDateString();
}
ToShortDateString method uses ShortDatePattern property of the CurrentCulture settings.
Probably your servers have different culture settings, that's why when you run this code, you get different string representations of your DateTime.
If you wanna get same representation in both server, set the same culture on both server in region and language settings or use custom date and time format specifiers like;
TxtIndate.Value = DateTime.Now.ToString("dd-MM-yyyy");
or as a better way as Matt mentioned, use InvariantCulture with string format like;
TxtIndate.Value = DateTime.Now.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture );
From the c# code it seems impossible that the same code produces two different time formats. So as far as I can tell, we have to find it somewhere else.
Maybe the source of the confusion is in two different types of input controls in your HTML output. One type=text, one type=date that could explain the different formatting since the HTML 5 date control renders differently. So one date is the server formatted value, the other is the browser, and possibly client culture, formatted value.
As other posters have said, this is due to the different cultures.
If having the same date format is important (caveat, users expect to see dates in the format they're used to for their culture) then you can always set it explicitly.
var myCultureDateFormat = new CultureInfo("en-US").DateTimeFormat;
// Short date string
var shortDate = DateTime.Now.ToString(myCultureDateFormat.ShortDatePattern);
// Long date string
var longDate = DateTime.Now.ToString(myCultureDateFormat.LongDatePattern);
Happy coding!

Converting string to decimal: how to handle the decimal separator in different cultures

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.

Convert number in textbox to float C#

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.

Format a date using the current thread culture Vs double digits for month and day?

I want to display some rows of data on a web page where one column is a DateTime.
I want the date format to be displayed based on the current thread culture.
Right now, I'm doing this (dt is a DateTime):
string s = dt.ToString(Thread.CurrentThread.CurrentCulture.DateTimeFormat);
It's working well, however, on some culture, months and days are represented as only one digit (hours too), for example:
8/8/2011 8:57:59 AM
I would like the date to be displayed like this:
08/08/2011 08:57:59 AM
It would be easier to read (and prettier) when there's a list of rows.
I saw that there's a String.format method I could use, but that makes the current culture irrelevant.
Is there a way to achieve what I'm trying to do?
The solution provided here might be useful.
I see only a single solution - you should obtain the current culture display format, patch it so that it meets your requirement and finally format your DateTime value using the patched format string.
Make a custom culture.
Base it on the current thread culture.
Modify the settings you want to override.
Then either set it back into the thread as the culture or use it temporarily during the format operation.
We currently do this to format all dates in an internationally unambiguous form ddMMMyyyy where MMM is only English three-letter abbreviations, yet obey local numeric formatting rules ./, etc.
The relevant properties to override would be here.
If you want to show it based on the current culture, then what is the problem? If you want a specific format, you have to specify that.
string text = myDateTime.ToString("{0:[your format]}");
I believe this defaults to the server format - but what if you try specifying "u" as the format code which will put the year first then I think two digits.
You can use
String.Format("{0:dd/MM/yyyy hh:MM PM ", yourDatetime)
The date separator / (slash) and time sepatator : (colon) will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator and DateTimeForma­tInfo.TimeSepa­rator.
EDIT: Forgot to add object param needed to the string.format
using System.Globalization;
private static CultureInfo defaultCulture = new CultureInfo("nl-NL");
public static CultureInfo GetCurrentCulture()
{
List<CultureInfo> badCultures = new List<CultureInfo>();
badCultures.Add(new CultureInfo("en-US"));
if (badCultures.Contains(System.Threading.Thread.CurrentThread.CurrentCulture))
return defaultCulture;
return System.Threading.Thread.CurrentThread.CurrentCulture;
}

comma separated double

Where can I set style in which double is writte by ToString() method ?
I am getting for example 2,2345 while I want to have 2.2345
thanks for ay hints,
bye
double a = 2.2345;
string b = a.ToString(CultureInfo.InvariantCulture);
You need to specify a FormatProvider, ususally as a CultureInfo.
For example:
string s = d1.ToString(System.Globalization.CultureInfo.InvariantCulture);
The Double.ToString() method is overloaded, so you can call it with a couple of different signatures to get the output you want.
In this case, your culture settings are affecting the output of the ToString() function. To get the result that you want, you should call Double.ToString(IFormatProvider), passing in CultureInfo.InvariantCulture:
myDouble.ToString(CultureInfo.InvariantCulture);
This should solve your issue.
For future reference, note that another common version of Double.ToString() is the Double.ToString(String) overload. The String parameter is a numeric format string, either one that is predefined or one that you specify. For example:
myDouble.ToString("format string here");
MSDN has a couple of articles on format strings: Standard Numeric Format Strings and Custom Numeric Format Strings.
If you would want the affect to be on your whole application. This could be set on initialization. Thus, note that this would mean an effective change on ALL cultures.
var culture = new CultureInfo(Thread.CurrentThread.CurrentCulture.Name);
culture.NumberFormat.NumberDecimalSeparator = ".";
Thread.CurrentThread.CurrentCulture = culture;
Then just:
string value = (1002.300).ToString();

Categories