How to convert reader.Read string to currency format in c#? - c#

I built the below code, trying to convert reader[BalanceAmt] to a currency, i.e. $23,456.78. I can't seem to get it to work. It's still returning "23456.782" Any ideas?
while (reader.Read())
{
string MyNum = reader["BalanceAmt"].ToString();
String.Format("{0:#,###0}", MyNum);
BalanceBox.Text = (MyNum);
}

If reader["BalanceAmt"] returns a string then to get your numeric formatting to work, you need to convert it into a number before converting it to currency - i.e.
var myNum = Convert.ToDecimal(reader["BalanceAmt"]);
BalanceBox.Text = myNum.ToString("C");
Note the "C" currency format specifier argument passed into the decimal.ToString method - see MSDN Decimal.ToString Method Documentation.
The Convert.ToDecimal method will throw an exception if reader["BalanceAmt"] contains anything that Convert.ToDecimal is unable to cope with (non-numeric characters).
You might want to put a try..catch around this, or if you don't want an exception to be thrown, use Decimal.TryParse inside an if check:
var balanceAmt = reader["BalanceAmt"];
if (decimal.TryParse(balanceAmt, out var myNum))
{
BalanceBox.Text = myNum.ToString("C");
}

while (reader.Read())
{
BalanceBox.Text = reader["BalanceAmt"].ToString("c");
}
In your code String.Format("{0:#,###0}", MyNum); MyNum never changes...only formatted.

Please use this:
BalanceBox.Text = String.Format("{0:#,###0}", Convert.ToDouble(MyNum));

Related

Format Decimal using toString() using latest frameworks. 4.7.2 or core 2.2

There are questions like mine but I feel they are outdated.
decimal decimalVar = 18000;
String formated = decimalVar.ToString("{0:N}");
print(formated);
I want this result:
18000.00
but my result is this:
{18000:n}
How can I do this?
You could use either
string formated = decimalVar.ToString("N2");
to use ToString() or
string formated = $"{decimalVar:N}";
to use string interpolation.
Both have the same result.
What you were attempting in your question suggests you were perhaps getting the two of these two mixed up.
just use ToString("###.00")like this
decimal num = 18000;
Console.WriteLine(num.ToString("##.00"));
result 18000.00
assume decimal value like decimal num = 18000.22m;
result would be 18000.22
What you're looking for is decimalVar.ToString("N2").
For more information, the documentation is at: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings
Additional examples:
double dblValue = -12445.6789;
Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture));
// Displays -12,445.68
Console.WriteLine(dblValue.ToString("N1",
CultureInfo.CreateSpecificCulture("sv-SE")));
// Displays -12 445,7
int intValue = 123456789;
Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture));
// Displays 123,456,789.0
EDIT: The "N" format adds separators and in your post your "expected result" does not so you may want to use "F" instead. decimalVar.ToString("F2")

Convert double to string, keep format - C#

Hi all. I have a double number (Ex: 0.000006). I want convert it to string type. But result is "6E-06". I dont want it, i want 0.000006".Thanks you so much
double a = 0.000006;
string resultString = a.toString();
I don't know many number after "." character
It's simple that if you want to show a number as exactly as what it looks, we can cast it to decimal and use the default ToString() like this:
var s = ((decimal)yourNumber).ToString();
//if yourNumber = 0.00000000000000000000000006
//just append the M after it:
var s = (0.00000000000000000000000006M).ToString();
Please check this article and find the format which suits your needs: http://www.csharp-examples.net/string-format-double/
Looks like this one is good enough:
String.Format("{0:0.00}", 123.4567);
Use String.Format() with the format specifier.
double a = 0.000006;
string formatted = String.Format("{0:F6}", a);
Try with the Roundtrip 'R' format specifier:
double a = 0.000006;
string resultString = a.ToString("R");
Double Rate_USD = Convert.ToDouble(txtRateUsd.Text);
string Rate_USD = txtRateUsd.Text;

Formatting String With LEading Zero's

I am trying to convert an object (coming from a SQL server), into a integer so I can format the number to have the correct amount of zero's in front of it.
For example:
If I were to have 25.6, I would need it to be 0025.6.
Now I have looked online on how to do this, but the methods that I have seen people post are not working for me. I am not entirely sure why. I am trying to format GlobalVariables.grossweightafter. I read the value GlobalVariables.grossweight from the SQL server, but then when I TryParse it, it loses its value. The code I have is below:
while (TransferRecord.Read())
{
//Pulling data from the SQL server. getting data for every line of code as specified.
GlobalVariables.baledate = TransferRecord["keyprinter_datetime"];
GlobalVariables.baleline = TransferRecord["pulp_line_id"];
GlobalVariables.baleid = TransferRecord["bale_id"];
GlobalVariables.grossweight = TransferRecord["bale_gross_weight"];
GlobalVariables.grossweightflag = TransferRecord["gross_value_flag"];
GlobalVariables.baleairdrypercent = TransferRecord["bale_airdry_pct"];
GlobalVariables.airdryflag = TransferRecord["airdry_value_flag"];
//Converting the date, and the baleid to fit in the string.
DateTime.TryParse(GlobalVariables.baledate.ToString(), out GlobalVariables.baledateafter);
int.TryParse(GlobalVariables.baleid.ToString(), out GlobalVariables.baleidafter);
int.TryParse(GlobalVariables.grossweight.ToString(), out GlobalVariables.grossweightafter);
GlobalVariables.grossweightafter.ToString("0000.0");
//Calling the WriteData method.
WriteData();
}
So I was wondering if anyone can catch what I am doing wrong, or they can help me out on the correct way to go about this.
What #Hans Passant was saying is that you need to assign the value returned from .ToString. That line should be:
GlobalVariables.grossweightafter = GlobalVariables.grossweightafter.ToString("0000.0");
The last lines should be
if(int.TryParse(GlobalVariables.grossweight.ToString(), out GlobalVariables.grossweightafter))
{
string grossWeightAfter = GlobalVariables.grossweightafter.ToString("0000.0");
//you need to save the string returned from the ToString-method somewhere or it will be lost.
///Alternatively, if GlobalVariables can contain strings aswell:
GlobalVariables.grossweightafter = GlobalVariables.grossweightafter.ToString("0000.0");
}
else
{
//React on value not being an int
}
Maybe you should try to use double.TryParse() method instead of int.TryParse(), because int does not have fractional part?
Also, you need to store ToString() result to a string variable. Your code should be like this:
GlobalVariables.grossweightafterstring = GlobalVariables.grossweightafter.ToString("0000.0");

Formatting Exception when parsing textbox into double

A = double.Parse(ABox.Text);
B = double.Parse(BBox.Text);
C = double.Parse(CBox.Text);
a = double.Parse(a_Box.Text);
b = double.Parse(b_Box.Text);
c = double.Parse(c_Box.Text);
Every time this code is run in my system, it throws an Formatting exception. The textBoxes are empty when the error appears, do they have to have at least a zero in them?
Yes
(An empty string can't be parsed into a double)
Instead of Parse you can consider using TryParse:
double number;
if (Double.TryParse(ABox.Text, out number))
{
...
}
else
{
...
}
Yes. Parse will throw an exception if the input is an empty string. You'll either need to check first whether the textbox is empty before parsing it or you can use TryParse.

Convert string to decimal with format

I need convert a String to a decimal in C#, but this string have different formats.
For example:
"50085"
"500,85"
"500.85"
This should be convert for 500,85 in decimal. Is there is a simplified form to do this convertion using format?
Some cultures use a comma to indicate the floating point. You can test this with the following code on an aspx page:
var x = decimal.Parse("500,85");
Response.Write(x + (decimal)0.15);
This gives the answer 501 when the thread culture has been set to a culture that uses the comma as floating point. You can force this like so:
var x = decimal.Parse("500,85", new NumberFormatInfo() { NumberDecimalSeparator = "," });
While decimal.Parse() is the method you are looking for, you will have to provide a bit more information to it. It will not automatically pick between the 3 formats you give, you will have to tell it which format you are expecting (in the form of an IFormatProvider). Note that even with an IFormatProvider, I don't think "50085" will be properly pulled in.
The only consistent thing I see is that it appears from your examples that you always expect two decimal places of precision. If that is the case, you could strip out all periods and commas and then divide by 100.
Maybe something like:
public decimal? CustomParse(string incomingValue)
{
decimal val;
if (!decimal.TryParse(incomingValue.Replace(",", "").Replace(".", ""), NumberStyles.Number, CultureInfo.InvariantCulture, out val))
return null;
return val / 100;
}
This will work, depending on your culture settings:
string s = "500.85";
decimal d = decimal.Parse(s);
If your culture does not by default allow , instead of . as a decimal point, you will probably need to:
s = s.Replace(',','.');
But will need to check for multiple .'s... this seems to boil down to more of an issue of input sanitization. If you are able to validate and sanitize the input to all conform to a set of rules, the conversion to decimal will be a lot easier.
Try this code below:
string numValue = "500,85";
System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("fr-FR");
decimal decValue;
bool decValid = decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat, out decValue);
if (decValid)
{
lblDecNum.Text = Convert.ToString(decValue, culInfo.NumberFormat);
}
Since I am giving a value of 500,85 I will assume that the culture is French and hence the decimal separator is ",". Then decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat,out decValue);
will return the value as 500.85 in decValue. Similarly if the user is English US then change the culInfo constructor.
There are numerous ways:
System.Convert.ToDecimal("232.23")
Double.Parse("232.23")
double test;
Double.TryParse("232.23", out test)
Make sure you try and catch...
This is a new feature called Digit Grouping Symbol.
Steps:
Open Region and Language in control panel
Click on Additional setting
On Numbers tab
Set Digit Grouping Symbol as custom setting.
Change comma; replace with (any character as A to Z or {/,}).
Digit Grouping Symbol=e;
Example:
string checkFormate = "123e123";
decimal outPut = 0.0M;
decimal.TryParse(checkFormate, out outPut);
Ans: outPut=123123;
Try This
public decimal AutoParse(string value)
{
if (Convert.ToDecimal("3.3") == ((decimal)3.3))
{
return Convert.ToDecimal(value.Replace(",", "."));
}
else
{
return Convert.ToDecimal(value.Replace(".", ","));
}
}

Categories

Resources