Formatting textbox c# and using it unformatted value - c#

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.

Related

C# format to thousand seperator

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");
}

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

Format a string using binding to format currency with no decimal places

I am looking to bind data in my datagrid to look like
$1,200
however, I have not found a way to do this.
I found this answer here which gives me
1,200 using {0:0,0}
but it does not have a dollar sign in front.
What do I need to use to accomplish this using the StringFormat member of a binding.
If I'm understanding your need correctly, you can just use the "C" formatter. It's the second one listed in the examples that links to.
decimal a = 1200;
return a.ToString("C"); // or string.Format("{0:C}", a);
You can also use "C0" if you, in fact, don't want any decimal places represented.
The major advantage of this over any custom format string is that this adjusts itself to culture variations client-side.

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
}

custom string format puzzler

We have a requirement to display bank routing/account data that is masked with asterisks, except for the last 4 numbers. It seemed simple enough until I found this in unit testing:
string.Format("{0:****1234}",61101234)
is properly displayed as: "****1234"
but
string.Format("{0:****0052}",16000052)
is incorrectly displayed (due to the zeros??): "****1600005252""
If you use the following in C# it works correctly, but I am unable to use this because DevExpress automatically wraps it with "{0: ... }" when you set the displayformat without the curly brackets:
string.Format("****0052",16000052)
Can anyone think of a way to get this format to work properly inside curly brackets (with the full 8 digit number passed in)?
UPDATE: The string.format above is only a way of testing the problem I am trying to solve. It is not the finished code. I have to pass to DevExpress a string format inside braces in order for the routing number to be formatted correctly.
It's a shame that you haven't included the code which is building the format string. It's very odd to have the format string depend on the data in the way that it looks like you have.
I would not try to do this in a format string; instead, I'd write a method to convert the credit card number into an "obscured" string form, quite possibly just using Substring and string concatenation. For example:
public static string ObscureFirstFourCharacters(string input)
{
// TODO: Argument validation
return "****" + input.Substring(4);
}
(It's not clear what the data type of your credit card number is. If it's a numeric type and you need to convert it to a string first, you need to be careful to end up with a fixed-size string, left-padded with zeroes.)
I think you are looking for something like this:
string.Format("{0:****0000}", 16000052);
But I have not seen that with the * inline like that. Without knowing better I probably would have done:
string.Format("{0}{1}", "****", str.Substring(str.Length-4, 4);
Or even dropping the format call if I knew the length.
These approaches are worthwhile to look through: Mask out part first 12 characters of string with *?
As you are alluding to in the comments, this should also work:
string.Format("{0:****####}", 16000052);
The difference is using the 0's will display a zero if no digit is present, # will not. Should be moot in your situation.
If for some reason you want to print the literal zeros, use this:
string.Format("{0:****\0\052}", 16000052);
But note that this is not doing anything with your input at all.

Categories