I am converting some VB6 code to C# and am having a problem duplicating certain functionality. I have a string representation of a number ex.6000 and a format specifier of ex. ###0.000.
VB6 Example:
Format(number, "########0.000") = "6.000"
I am having trouble finding the C# equivalent to duplicate this functionality. The methods I have tried with ToString() but they are more for formatting the actual number rather than more of an overlay format like VB6 is doing.
C# Example:
number.ToString("########0.000", CultureInfo.InvariantCulture) = 6000.000
Personally, I think you should simply revisit your inputs and numeric specifiers to be more appropriate, but: you could cheat with:
string s = number.ToString(#"########0\.000", CultureInfo.InvariantCulture)
The \. is now not the decimal point specifier, but a literal. Horrible horrible answer. Please don't do it.
you can use the "FormatNumber" function instead
Related
Numerical formatting of int, double, decimal can be simply achieved via using Standard Numerical Formatter for example assuming Culture is "en-GB":
int value = 1000;
Console.WriteLine(value.ToString("C0")); // Would output £1,000
However I am wondering if there is a simple way to format a string to something of the same effect as above. For example:
string amount = "£2000"; // Would want to format to "£2,000"
Is there a way to format this string so that the thousands separator is added in the correct position?
Given it's a string I don't think numerical formatting would work without converting the string to a numerical data type beforehand:
var result = Int32.Parse("£2000", NumberStyles.AllowCurrencySymbol, new CultureInfo("en-GB"));
Console.WriteLine(result.ToString("C0", new CultureInfo("en-GB"))); // Outputs £2,000
However its a bit verbose to convert string to int then back to string. Is there is a simpler way to do this given that the starting string has the currency symbol?
Given it's a string I don't think numerical formatting would work without converting the string to a numerical data type beforehand
Indeed.
Is there is a simpler way to do this given that the starting string has the currency symbol?
No. And I seriously doubt that such a feature would ever be added and/or welcomed by the developer community. A formal specification for such a feature would be a complexity nightmare.
Of course, in your particular case, if you are sure that your string always consists of "currency symbol + sequence of digits without comma or period", you could develop a string-based solution optimized for your use case (for example, a fancy regular expression). However, I think that your current solution is both readable and maintainable and you would do your future self a favor by keeping it that way. If you need it multiple times, extract it into a method.
I am looking for a strategy to implement different currencies in my system.
For GB I use pounds locale and it works ok with numbers like "7.55", but as soon I change locale to Spanish for example I get the "7,55" number and I cannot handle it.
So the first thing is that I calculate some amount with JavaScript client side and JavaScript cannot calculate comma numbers, nor I can parseFloat, nor converting to decimal number if I don't replace commas with numbers like:
input.val().replace(',', '.');
I mean I don't understand how to handle this properly in scenarios when you have to make payment. When to convert for calculations, etc.
Is there any proper way to do this in .net with JavaScript help? Just need some tips.
In c#, you can use CultureInfo.InvariantCulture for this. You have a full snippet about currency here.
string str = "42.5";
float numFloat = float.Parse(str, CultureInfo.InvariantCulture);
Learn more from the msdn.
Just something that i was wondering about.
In Europe the comma us mostly used for decimals (like 20,001) but outside Europe the point is mostly used (like 20.001)
How does c# handle this ?
In case of a application that will be used by Europe and non-Europe people, do you need to worry about the above when programming ?
Just curious about this.
As far as the programming language is concerned, the decimal point separator is always ., and the punctuation used to separate function arguments is always ,. Changing that based on the spoken language of the programmer would be too confusing.
For the user interface, there are formatting functions in the CultureInfo class that can produce a floating point number representation that uses the decimal point separator and thousands separator of your choice. (Or, for cultures that group digits of a number differently than in triplets, the formatting functions can handle that too.)
CultureInfo handles that situation.
Take a look at this
// format float to string
float num = 1.5f;
string str = num.ToString(CultureInfo.InvariantCulture.NumberFormat); // "1.5"
string str = num.ToString(CultureInfo.GetCultureInfo("de-DE").NumberFormat); // "1,5"
Yes, c# (and really, the whole .NET framework) have the concept of Cultures for this purpose:
http://msdn.microsoft.com/en-us/library/bz9tc508.aspx
and
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=VS.100).aspx
You should use CultureInfo Class to handle it. Just read and write with correct formatter.
That depends on what exactly you do... .NET is usually aware of the current settings of the machine/OS and uses those...
You should look into this and see whether any of it is relevant in your case...
When using string.Format(string, object[]) it throws an exception if string contains more format specifiers ({0}, {1:dd-MM-yyyy} etc.) than object[].Length.
I'd like to also throw an exception if object[].Length contains more specifiers. There seems to be no built-in way to do it, so I'm trying to get the number of format specifiers in the input string. The tricky bit is that stuff like {{something}} or {0:dd-MM-yyyy} is allowed.
Does anyone know an easy or even built-in way to get the number of format specifiers in a string? I'm currently trying to build a regex, but maybe there is an easier way?
Looks like someone has already built a regex for this: Is there a better way to count string format placeholders in a string in C#?
Is there a C# equivalent for the VB.NET FormatNumber function?
I.e.:
JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2);
In both C# and VB.NET you can use either the .ToString() function or the String.Format() method to format the text.
Using the .ToString() method your example could be written as:
JSArrayString += "^" + (inv.RRP * oCountry.ExchangeRate).ToString("#0.00")
Alternatively using the String.Format() it could written as:
JSArrayString = String.Format("{0}^{1:#0.00}",JSArrayString,(inv.RRP * oCountry.ExchangeRate))
In both of the above cases I have used custom formatting for the currency with # representing an optional place holder and 0 representing a 0 or value if one exists.
Other formatting characters can be used to help with formatting such as D2 for 2 decimal places or C to display as currency. In this case you would not want to use the C formatter as this would have inserted the currency symbol and further separators which were not required.
See "String.Format("{0}", "formatting string"};" or "String Format for Int" for more information and examples on how to use String.Format and the different formatting options.
Yes, the .ToString(string) methods.
For instance,
int number = 32;
string formatted = number.ToString("D4");
Console.WriteLine(formatted);
// Shows 0032
Note that in C# you don't use a number to specify a format, but you use a character or a sequence of characters.
Formatting numbers and dates in C# takes some minutes to learn, but once you understand the principle, you can quickly get anything you want from looking at the reference.
Here's a couple MSDN articles to get you started :
Standard Numeric Format Strings
Formatting Types
You can use string formatters to accomplish the same thing.
double MyNumber = inv.RRP * oCountry.ExchangeRate;
JSArrayString += "^" + MyNumber.ToString("#0.00");
While I would recommend using ToString in this case, always keep in mind you can use ANY VB.Net function or class from C# just by referencing Microsoft.VisalBasic.dll.