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.
Related
I have a line of code, something like:
mbar.HealthLabel.text = String.Format("{0:0.0}", _hp);
Output is: 2.25 for example. Is it possible to escape a dot from the output string view with String.Format function ?
For. ex. 225,
To make my question more clear, I need the same effect like:
Math.Floor(_hp * 100).ToString();
But need to do it by String.Format template.. Thanks.
Simply you can do it this way
double value = 1.25;
var stringValue = string.Format("{0:0}", value * 100, CultureInfo.InvariantCulture); //125
EDIT:
More general solution would be to Replace the dot with empty string as stated in the comments.
double value = 1.25;
var stringValue = value.ToString(CultureInfo.InvariantCulture).Replace(".",string.Empty);
EDIT2: Also there is another general idea that do not use Replace function (but also it does not use the String.Format)
var stringValue = string.Join("", value.ToString().Where(char.IsDigit));
Also another similar idea:
var stringValue = new string(value.ToString().Where(char.IsDigit).ToArray());
First of all, please read my comment to the question. As i mentioned there, string format for numeric values depends on regional settings. So, below line
mbar.HealthLabel.text = String.Format("{0:0.0}", _hp);
will return: 2,25 (as to the polish numeric standard)
In my opinion you need something like this:
mbar.HealthLabel.text = String.Format("{0:D}", Math.Floor(_hp*100));
For furhter details, please see:
Standard Numeric Format Strings
Custom Numeric Format Strings
Up to Microsoft.NET Framework 4.7 there is no way to solve this when we are only allowed to modify the format string ("template"). All solutions require to either:
Post-process the resulting string. Here, the closest for the special case with two decimals may be the % format
Compute the numeric argument first to make it integer
Write and apply a custom IFormatProvider implementation
If you want to eliminate the decimal separtor ("escape the dot", as you've put it), try replacing the decimal separator with empty string:
string result = String
.Format("{0:0.0}", _hp)
.Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, "");
Struggling with the basics - I'm trying to code a simple currency converter. The XML provided by external source uses comma as a decimal separator for exchange rate (kurs_sredni):
<pozycja>
<nazwa_waluty>bat (Tajlandia)</nazwa_waluty>
<przelicznik>1</przelicznik>
<kod_waluty>THB</kod_waluty>
<kurs_sredni>0,1099</kurs_sredni>
</pozycja>
I already managed to load the data from XML into a nifty list of objects (kursyAktualne), and now i'm trying to do the math. I'm stuck with conversion.
First of all i'm assigning "kurs_sredni" to a string, trying to replace "," with "." and converting the hell out of it:
string kursS = kursyAktualne[iNa].kurs_sredni;
kursS.Replace(",",".");
kurs = Convert.ToDouble(kursS);
MessageBox.Show(kurs.ToString());
The messagebox show 1099 instead of expected 0.1099 and kursS still has comma, not dot.
Tried toying with some cultureInfo stuff i googled, but that was too random. I need to understand how to control this.
Just use decimal.Parse but specify a CultureInfo. There's nothing "random" about it - pick an appropriate CultureInfo, and then use that. For example:
using System;
using System.Globalization;
class Test
{
static void Main()
{
var french = CultureInfo.GetCultureInfo("fr-FR");
decimal value = decimal.Parse("0,1099", french);
Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); // 0.1099
}
}
This is just using French as one example of a culture which uses , as a decimal separator. It would probably make sense to use the culture of the origin of the data.
Note that decimal is a better pick for currency values than double - you're trying to represent an "artificial" construct which is naturally specified in base10, rather than a "natural" continuous value such as a weight.
(I would also be wary of a data provider who provides data in a non-standard format. If they're getting that wrong, who knows what else they'll get wrong. It's not like XML doesn't have a well-specified format for numbers...)
It is because Replace method returns new string with replaced characters. It does not modify your original string.
So you need to reassign it:
kursS = kursS.Replace(",",".");
Replace returns a string. So you need an assignment.
kursS = kursS.Replace(",", ".");
There is "neater" way of doing this by using CulturInfo. Look this up on the MSDN website.
You replace result isn't used, but the original value that doesn't contain the replace.
You should do:
kursS = kursS.Replace(",", ".")
In addition this method isn't really safe if there are thousands-separators.
So if you are not using culture settings you should do:
kursS = kursS.Replace(".", "").Replace(",", ".")
Maybe someone in either of the camps can tell me whats going on here:
Python:
temp = int('%d%d' % (temp2, temp3)) / 10.0;
I'm working on parsing temperature data, and found a piece of python that I can't understand. What is going on here? Is python adding together two numbers here and casting them to int, and then divide by 10?
C# might look like:
temp = ((int)(temp2+temp3))/10;
But I am not sure what that % does? Data is jibberish so I don't know what is correct translation for that line in python to C#
In C# it looks like:
var temp = int.Parse(temp2.ToString() + temp3.ToString())/10f;
or:
var temp = Convert.ToInt32(string.Format("{0}{1}", temp2, temp3))/10f;
this is similar: What's the difference between %s and %d in Python string formatting?
name = 'marcog'
number = 42
print '%s %d' % (name, number)
will print marcog 42. Note that name is a string (%s) and number is an integer (%d for decimal).
See
http://docs.python.org/library/stdtypes.html#string-formatting-operations
for details.
So it seems like the "%" is just telling python to put the values on the right into the placeholders on the left.
from the documentation linked in the answer I quoted:
Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language. If format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.
Would probably want to set up a python script and try it out, placing your own values into the variables.
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
How can I change values in string from 0,00 to 0.00? - only numeric values, not all chars "," to "."
FROM
string myInputString = "<?xml version=\"1.0\"?>\n<List xmlns:Table=\"urn:www.navision.com/Formats/Table\"><Row><HostelMST>12,0000</HostelMST><PublicMST>0,0000</PublicMST><TaxiMST>0,0000</TaxiMST><ParkMST>0,0000</ParkMST><RoadMST>0,0000</RoadMST><FoodMST>0,0000</FoodMST><ErrorCode>0</ErrorCode><ErrorDescription></ErrorDescription></Row></List>\n";
TO
string myInputString = "<?xml version=\"1.0\"?>\n<List xmlns:Table=\"urn:www.navision.com/Formats/Table\"><Row><HostelMST>12.0000</HostelMST><PublicMST>0.0000</PublicMST><TaxiMST>0.0000</TaxiMST><ParkMST>0.0000</ParkMST><RoadMST>0.0000</RoadMST><FoodMST>0.0000</FoodMST><ErrorCode>0</ErrorCode><ErrorDescription></ErrorDescription></Row></List>\n";
Thanks for answers, but I mean to change only numeric values, not all chars "," to "."
I don't want change string from
string = "<Attrib>txt txt, txt</Attrib><Attrib1>12,1223</Attrib1>";
to
string = "<Attrib>txt txt. txt</Attrib><Attrib1>12.1223</Attrib1>";
but this one is ok
string = "<Attrib>txt txt, txt</Attrib><Attrib1>12.1223</Attrib1>";
Try this :
Regex.Replace("attrib1='12,34' attrib2='43,22'", "(\\d),(\\d)", "$1.$2")
output : attrib1='12.34' attrib2='43.22'
The best method depends on the context. Are you parsing the XML? Are you writing the XML. Either way it's all to do with culture.
If you are writing it then I am assuming your culture is set to something which uses commas as decimal seperators and you're not aware of that fact. Firstly go change your culture in Windows settings to something which better fits your culture and the way you do things. Secondly, if you were writing the numbers out for human display then I would leave it as culturally sensative so it will fit whoever is reading it. If it is to be parsed by another machine then you can use the Invariant Culture like so:
12.1223.ToString(CultureInfo.InvariantCulture);
If you are reading (which I assume is what you are doing) then you can use the culture info again. If it was from a human source (e.g. they typed it in a box) then again use their default culture info (default in float.Parse). If it is from a computer then use InvariantCulture again:
float f = float.Parse("12.1223", CultureInfo.InvariantCulture);
Of course, this assumes that the text was written with an invariant culutre. But as you're asking the question it's not (unless you have control over it being written, in which case use InvariantCulture to write it was suggested above). You can then use a specific culture which does understand commas to parse it:
NumberFormatInfo commaNumberFormatInfo = new NumberFormatInfo();
commaNumberFormatInfo.NumberDecimalSeperator = ",";
float f = float.Parse("12,1223", commaNumberFormatInfo);
I strongly recommend joel.neely's regex approach or the one below:
Use XmlReader to read all nodes
Use double.TryParse with the formatter = a NumberFormatInfo that uses a comma as decimal separator, to identify numbers
Use XmlWriter to write a new XML
Use CultureInfo.InvariantCulture to write the numbers on that XML
The answer from ScarletGarden is a start, but you'll need to know the complete context and grammar of "numeric values" in your data.
The problem with the short answer is that cases such as this get modified:
<elem1>quantity<elem2>12,6 of which were broken</elem2></elem1>
Yes, there's probably a typo (missing space after the comma) but human-entered data often has such errors.
If you include more context, you're likely to reduce the false positives. A pattern like
([\s>]-?$?\d+),(\d+[\s<])
(which you can escape to taste for your programming language of choice) would only match when the "digits-comma-digits" portion (with optional sign and currency symbol) was bounded by space or an end of an element. If all of your numeric values are isolated within XML elements, then you'll have an easier time.
string newStr = myInputString.Replace("0,00", "0.00");
While you could theoretically do this using a Regex, the pattern would be complex and hard to to test. ICR is on the right track, you need to do this based on culture.
Do you know that your numbers are always going to be using a comma as a decimal separator instead of a period? It looks like you can, given that Navision is a Danish company.
If so, you'll need to traverse the XML document in the string, and rewrite the numeric values. It appears you can determine this on node name, so this won't be an issue.
When you convert the number, use something similar to this:
here's what you want to do:
internal double ConvertNavisionNumber(string rawValue)
{
double result = 0;
if (double.TryParse(rawValue, NumberStyles.Number, new CultureInfo("da-DK").NumberFormat, out result))
return result;
else
return 0;
}
This tells the TryParse() method that you're converting a number from Danish (da-DK). Once you call the function, you can use ToString() to write the number out in your local format (which I'm assuming is US or Canadian) to get a period for your decimal separator. This will also take into account numbers with different thousands digit separator (1,234.56 in Canada is written as 1 234,56 in Denmark).
ConvertNavisionNumber("4,43").ToString()
will result in "4.43".
ConvertNavisionNumber("1 234").ToString()
will result in "1,234".
if the , is not used anywhere else but number with in the string you can use the following:
string newStr = myInputString.Replace(",", ".");