Problem passing decimal value to database (Access) - c#

I want to pass decimal value to database table. When I send value 1,5 to database then save value as 15.
Code:
txtKm.Text="1,5";
zelezniceDataSet.VozniRediRow row;
row.Km = decimal.Parse(txtKm.Text);
zelezniceDataSet.VozniRedi.AddVozniRediRow(row);
vozniRediTableAdapter.Update(zelezniceDataSet.VozniRedi);
When debug decimal parsing the value is correct (1.5)

You probably want to look at an overloaded form of decimal.Parse that accepts a culture-specific format option. My guess is decimal.Parse sees your comma as a thousands-separator and just removes it.

seems to me that decimal.Parse is ignoring the comma ... if you pass "1.5" is the correct value saved? If so then you need to use the overload that takes the culture to use when parsing Decimal.Parse(String, NumberStyles) and pass it the correct number style for the language you are using.
EDIT ... more info ..
decimal.Parse(test, CultureInfo.GetCultureInfo("EN-us").NumberFormat );
will output 15 for test = "1,5" because in English the "," char is the thousands separator
decimal.Parse(test, CultureInfo.GetCultureInfo("NL-nl").NumberFormat );
will output 1.5 for test = "1,5" because in Dutch the "," char is the decimal separator
Hope this helps :)

Related

Float.Parse() ignoring decimal comma

I am getting some percent values from a database and I need to format them to have the correct thousands seperator, number of decimal places and a percent sign on the end.
I tried this:
string text = "105,3"; //example, formatting like database input
string format = "#,##0.##";
e.Row.Cells[i].Text = double.Parse(text).ToString(format);
Weirdly this returns 1053,00%. How do I make it so it returns 105,30%? (The decimal comma is because the system locale is german, so it's how it is supposed to be)
edit: replacing the comma with a period results in 10530.00%. Nothing makes sense to me anymore.
edit2: the float.Parse() actually works just fine. the ToString() messes everything up. I played around with using different cultural settings and format strings (switching comma and period) but it only makes it worse again.
Pass the current Culture to the Parse method: double.Parse( text, CultureInfo.CurrentCulture )
However, this only works on systems that use a locale that has the comma as a decimal separator.
If you want this to work on other locales you should replace CurrentCulture with the specific CultureInfo instance that used when inputting data in the first place.
The title is misleading. The actual problem was the ToString() function. In the format string I added the % sign, which, to be fair, I didn't add in the original post because I forgot about it. It automatically multiplies the number by 100. So my format string is now "#,##0.00\%".

String format number with three sections as String.Format(“{0:$#,##0.00;($#,##0.00);Zero}”, value);

I'm implementing string format number with three sections as
DataFormatString="{}{0:$#,##0.00;($#,##0.00);''}"
i.e:
input 120 result $120.00
input -120 result ($120.00)
input 0 result ''
the problem is the dollar sign is hard-coded and I want my app to globalization. I tried some thing like this:
DataFormatString="{}{0:C;C;''}"
but it doesn't help.
Perhaps try taking this approach:
var DataFormatString="$#,##0.00;($#,##0.00);''";
var amount = 1342.56m;
var formatted =
amount
.ToString(DataFormatString)
.Replace("$", CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol);
The only downside is that it won't correctly place the currency symbol at the end of the number if that's the standard for that currency.
You can use the overload of string.Format with IFormatProvider like so:
string DataFormatString="{0:C}";
string output = string.Format(CultureInfo.CreateSpecificCulture("culture"),DataFormatString,input)
Demo
However, as Soner Gonul observes, this still won't generate '' as output for 0.
As far as I know, there is no direct format to supply that 3 results you want for those inputs.
For first two format, you can use The "C" format specifier with en-US culture (which has $ as a CurrencySymbol) using 2 as a precision specifier like;
(120).ToString("C2", CultureInfo.GetCultureInfo("en-US")) // $120.00
(-120).ToString("C2", CultureInfo.GetCultureInfo("en-US")) // ($120.00)
But for 0, this generates $0.00 which is not what you want.
As a better solution, check Enigmativity's answer instead which handles 0 value as well.

System.Console.Write("{0}{1:N2} {2}" what's {1:N2} referring to?

i know 0 is for the first element in the array etc... but what's 1:N2?
The format to be applied to the data. In this case two decimal number.
http://msdn.microsoft.com/en-us/library/aa720653(v=vs.71).aspx
{1:N2} means that the second parameter is formatted as a number with thousand seperators and a precision of 2 digits.
The index "1" to the left of the colon specifies the second of the arg parameters (zero-based indexing). The string "N2" to the right of the colon specifies the format to use on that parameter. Specifically, N2 means group-separator numeric format with 2 decimal places; for details, see the documentation on standard format strings at http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
In general, the format specifier is of the form { index[,alignment][ : formatString] }; for details, see the documentation: http://msdn.microsoft.com/en-us/library/ttxecb1c.aspx
That is Numeric formatting the second element. Formatting in .Net can be done on different data types like number, dates, enums. you can also create custom formats. you can get started on formatting here
Formatting Types

How to insert a thousand separator (comma) with convert to double

I am trying to format the contents of a text box:
this.lblSearchResults1.Text =
Convert.ToDouble(lblSearchResults1.Text).ToString();
How do I amend this so that I the text includes comma/thousand separators?
i.e. 1,000 instead of 1000.
Looking at the standard numeric format strings:
You can most easily use 'N' which will do the right thing based on the user culture, so in your case you can just add "N" as a param to the ToString
([double]12345.67).ToString("N")
12,345.67
For complete custom control, use ... .ToString("#,##0.00") or variations thereof. The . and , will be replaced by culture dependent symbols. In most of europe you'd get 1.234,56.
Another useful picture is 0.0#.
To use a pattern depending on the users (or on a selected) culture, use The Numeric ("N") Format Specifier, as in .ToString("N") or "... {0:N}".
The easiest way to do it would be something like:
Convert.ToDouble("1234567.12345").ToString("N")
If you want to control the decimal places you can do something like:
Convert.ToDouble("1234567.12345").ToString("N3")
In general look at the overloads on ToString for more exciting possibilities.
If you take a closer look at Standard Numeric Format Strings you can try one of the following:
.ToString("n", CultureInfo.GetCultureInfo("en-US"))
.ToString("n", CultureInfo.GetCultureInfo("de-DE"))
.ToString("n", CultureInfo.CurrentCulture)
An alternative to the above mentioned responses would be to use
this.lblSearchResults1.Text = String.Format("{0:N}", Convert.ToDouble(lblSearchResults1.Text))
If you wanted decimal places, just enter the amount of decimal places you wish to have after the N. The following example will return the value with 2 decimal places.
this.lblSearchResults1.Text = String.Format("{0:N2}", Convert.ToDouble(lblSearchResults1.Text))
See http://msdn.microsoft.com/en-us/library/system.string.format.aspx for more information.
double.Parse(Amount).ToString("N");
Do not cast integral to double to do this!
Use NumberFormatInfo helper class, e.g:
var nfi = new NumberFormatInfo() {
NumberDecimalDigits = 0,
NumberGroupSeparator = "."
};
var i = 1234567890;
var s = i.ToString("N", nfi); // "1.234.567.890"

Custom Numeric Format Strings: Dynamic Decimal Point

I am trying to format a double in C# such that it uses the thousand separator, and adds digits upto 4 decimal places.
This is straight forward except that I dont want to have the decimal point if it is an integer. Is there a way to do this using the custom numeric format strings rather than an if statement of tenary operator?
Currently I have:
string output = dbl.ToString(dbl == (int)dbl ? "#,##0" : "#,##0.####");
Thanks
I believe your second format string of "#,##0.##" should be exactly what you want -- the # format character is a placeholder that will NOT display zeros.
If you had "#,###.00" then you would get trailing zeros.
test code:
double d = 45.00;
Console.Writeline(d.ToString("#,##0.##"));
Gives output of "45". Setting d to 45.45 gives output "45.45", which sounds like what you're after.
So you had the answer after all! ;)
Incidentally, there's a handy cheat-sheet for format strings (amongst other handy cheat-sheets) at http://john-sheehan.com/blog/net-cheat-sheets/
No, there is not any built-in format string for this. Your current solution is the best way to accomplish this.
MSDN lists both the standard numeric format strings and custom numeric format strings, so you should be able to see for yourself that none directly matches your needs.

Categories

Resources