C# format to thousand seperator - c#

I am trying to format user input to a thousand seperator format. I tried the code here, but it keeps breaking the application:
Amt.Text = String.Format("{0:0,0.00}", Convert.ToDouble(Amt));
So when the user inputs 3566412, then it needs to convert automatically to 3,566,412

You are trying to convert the control (named Amt) to a double, which is a bad idea since you want to convert the text of the control (Amt.Text). I would suggest to use a decimal since that is more precise and will not cause floating point issues:
Amt.Text = String.Format("{0:0,0.00}", Convert.ToDecimal(Amt.Text));
Another thing to consider is to use a control that can mask itself, so you don't need to replace the text yourself every time.

You might want to check out Standard Numeric Format Strings at MSDN
Then you could do something like
Amt.Text = inputnumber.ToString("N");
Which will format 3566412 to 3,566,412.0
If you want to take it directly from the textbox, you could do something like this, which checks if the text can be parsed before setting the text
double result = 0;
if (double.TryParse(Amt.Text, out result)
{
Amt.Text = result.ToString("N");
}

Related

string.format - Commas as decimal separator

Given the input 123.45, I'm trying to get the output 123,45 via String.Format.
Because of the system I'm working in, the actual format strings (e.g. {0:0.00}) are saved in a config file and transformed later down the pipeline.
Editing the config file to add a new format is "safe" and I can get this through quite quickly. Editing the actual parser later down the line is "risky" so will need a more significant QA resource and I need to avoid this.
As a result, some caveats:
I only have access to string.Format(pattern, input). No overloads.
I cannot send a localisation. I know that if I send string.Format(new System.Globalization.CultureInfo("de-DE"), "{0:0.00}", 123.45) then I've got what I need. But I cannot pass the localisation.
So can it be done?
Is there any format I can pass to string.Format which will transform 123.45 into 123,45?
If you can you multiply the input by 100 then the following should work:
double input = 123.45;
string pattern = "{0:###\\,##}";
var result = String.Format(pattern, input*100);
Just for the fun of it :)
double value =123.45;
Console.WriteLine(String.Format("{0:#0.00}\b\b\b,", value));
This of course only works when there is a cursor, like in the console, otherwise the backspace control characters have no effect.
Sorry, but i can't think of a real way in accomplishing this.

String to Double Conversion (Comma to dot issue)

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(",", ".")

Parsing Text from a Masked Text Box

I have a WinForms application written in C#
I have until recently many textboxes on my forms where the user inputs financial amounts. I have not incorporated any form of mask initially and whenever I need to work with the values input by the users I would Parse the text from each box into Decimal values with Decimal.Parse;
However I have been asked to make the textboxes look like financial amounts
i.e. £1,050.75 rather than 1050.75
I therefore started to change the textboxes into MaskedTextBox and gave them a Mask of £#,##0.00
However now each attempt to Parse the text from the MaskedTextBoxes gives an error 'Input string not in the correct format'.
How do I obtain the users input from the MaskedTextBox and parse into decimal format to work with?
Should I be using MaskedTextBox at all, or is there another way of showing a financial type formatting on the form, without effecting the Decimal.Parse method?
When you are getting the value from Maskedtextbox, it is taking the value as £#,##0.00 . so the symbol will not be converted to decimal. Try to remove the symbol and convert the value to decimal. like
string val= maskedTextBox1.Text.Replace("£","");
Decimal.Parse(val);
You can use a format option with AllowCurrencySymbol. It has to match the currency symbol of the culture. This code I converted from VB so I hope it's correct.
Application.CurrentCulture = New Globalization.CultureInfo("en-GB");
Decimal.Parse("£12,345.67", Globalization.NumberStyles.AllowThousands | Globalization.NumberStyles.AllowDecimalPoint | Globalization.NumberStyles.AllowCurrencySymbol);
Also, see this question if you don't want to change the culture:
Problem parsing currency text to decimal type
You can check MaskFull to see if text is properly enter and then apply anti-mask (by removing that, what your mask is adding).
Unfortunately, I am not aware about automated unmasking. But you can do something like:
if(maskedTextBox1.Mask)
{
var enteredText = maskedTextBox1.SubString(1).Replace(",", null); // remove pound symbol and commas
// ... parse as with normal TextBox
}

Formatting textbox c# and using it unformatted value

I´m using some textboxes to show totals, subtotals and discounts. I´m converting decimals to string to represent them in the textbox. Also, I would like to have the "$" at the beginning.
I have achieved this by using this:
tbx_total.Text = total.ToString("$ ##0.##");
Graphically, this is working great, but my big problem is that I need that textbox value to calculate other ones. Basically, I get a formatting error during runtime when I try to convert that textbox text to decimal. Obviously, this is due to the ToString("$ ##0.##") format. Is there any way to get the value without the format?
One simple solution will be:
tbx_total.Text = total.ToString("$ ##0.##");
tbx_total.Tag = total;
Then use tbx_total.Tag property for further usage.
When reading it back in you can parse with NumberStyles to get your desired effect. There is a number of bit-wise operations on NumberStyles so I suggest researching how to use them for more flexibility:
double.Parse(total, NumberStyles.Currency);
Also I tend to like this for formatting currency a bit more but purely stylistic.
String.Format("{0:C}", total);
Note: Parsing back and forth does incur some overhead so depending on the amount of data it may be more wise to offload the value to an object and reference that when you need the decimal value again.
As an alternative, you can do this, whenever you read the value:
double value = 0;
if (!double.TryParse(tbx_total.Text.TrimStart(new char[] { '$', ' ' }), out value))
{
//Ooops... not a valid number
}
So here you basically remove the added '$' and space before the number enabling you to parse it as a double. This way you can check if the number has been entered correctly (provided that the user can edit the textbox.
I think you should store your original values (decimal) in a DataTable or some other collection and use these values to calculate what you need.
So you can format decimal values in any format you like without warry about how to convert back from strings.

how to change values in string from 0,00 to 0.00

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(",", ".");

Categories