How to convert the text from a label into double - c#

I am new to C# and just started to learn how to code. I was trying to convert and sum an amounts for several items displayed in a label, then displays the total in another label.I used parse to convert the values to double ,but I've frequently got an error message saying that"cannot implicitly convert type int to string.Here is a sample of my code.
int Cost;
double total = 0;
costLabel.Text = Convert.ToInt32(priceLabel2.Text);
Cost = int.Parse(priceLabel2.Text);
total += double.Parse(priceLabel2.Text);
costLabel.Text = total.ToString("c");
can any one help me to solve this problem?

Please, mind types; your code amended:
// Are you sure that price is integer? What about 4.95$?
// More natural choice is double (decimal is the best for the currency)
double Cost;
// Let's preserve double (but decimal is a better choice)
double total = 0;
// string assigned to string; no Convert.ToInt32
// It's useless line, however, since costLabel.Text = total.ToString("c");
// will rewrite the label
costLabel.Text = priceLabel2.Text;
// Since cost is not an integer value
Cost = double.Parse(priceLabel2.Text);
// You don't want to parse twice
total += Cost;
costLabel.Text = total.ToString("c");
A better choice is to use decimal for currency:
decimal total = 0m;
//TODO: it seem's that you want to add some logic here; otherwise total == cost
decimal cost = decimal.Parse(priceLabel2.Text);
total += cost;
costLabel.Text = total.ToString("c");

The problem is in the line costLabel.Text = Convert.ToInt32(priceLabel2.Text);. You have a lot of unnecessary code, so it could all be simplified to the following:
double total = double.Parse(priceLabel2.Text);
costLabel.Text = total.ToString("c");

You are assigning integers to strings, that won't work. You are also performing multiple operations on the same input. For currencies, you must use decimal since that is a safer (more precise) data type.
decimal total = 0;
...
decimal price = Convert.ToDecimal(priceLabel2.Text);
total += price;
costLabel.Text = total.ToString("c");
If you want to validate the input first, you should use decimal.TryParse:
if (decimal.TryParse(priceLabel2.Text, out decimal price))
{
total += price;
}
else
{
MessageBox.Show("Input is not a valid decimal.");
}

costLabel.Text property type is a string.
costLabel.Text = priceLabel2.Text;

costlLabel.Text is a string and you try to give it an integer value:
costLabel.Text = Convert.ToInt32(priceLabel2.Text);
use this instead:
costLabel.Text = priceLabel2.Text;

Related

How to get the next decimal given a decimal/precision

I want to determine the next decimal after a certain decimal programmatically.
For example, I have the decimal 0.0000041
I want to programmatically generate 0.0000042 in a function.
If I ran the function again after running it with 0.0000042 the new number would be 0.0000043
If I ran the function with the decimal being 0.0000049 the new number would be 0.0000050 etc....
Is there a way to do this?
I do not know where to start or what references to look at to do something like this.
Thank you.
You seem to be looking for something like this: (Check below if you want to specify the precision manually)
static decimal GetNextDecimal(decimal input)
{
int count = BitConverter.GetBytes(decimal.GetBits(input)[3])[2];
return input + (1m / (decimal)Math.Pow(10, count));
}
Usage:
decimal num1 = 0.0000041m;
decimal num2 = 0.00002m;
decimal next = GetNextDecimal(num1);
decimal next2 = GetNextDecimal(num2);
Console.WriteLine(next);
Console.WriteLine(next2);
Output:
0.0000042
0.00003
I used a little help of this answer to get the number of the decimal places.
If you originally wanted to specify the precision manually, you can use the following instead:
static decimal GetNextDecimal(decimal input, int precision)
{
return input + (1m / (decimal)Math.Pow(10, precision));
}
..which allows you to do something like this:
decimal num1 = 0.003m;
decimal next = GetNextDecimal(num1, 3);
decimal next2 = GetNextDecimal(num1, 4);
Console.WriteLine(next);
Console.WriteLine(next2);
Output:
0.004
0.0031

Need only 2 digits after decimal point

I want my function to return value with only 2 decimal places. I have tried following code :
private static double CalculateSlabTax(int nSlabStartTaxable,
int nSlabEndTaxable,
float fSlabRate)
{
double dblSlabResult = 0;
try
{
dblSlabResult = (nSlabStartTaxable - nSlabEndTaxable) * fSlabRate;
dblSlabResult = Math.Round(dblSlabResult , 2);
return dblSlabResult;
}
catch (Exception)
{
return -1;
}
}
Expected output is : dblSlabResult = ####.## - two digits (eg. 1002.05)
Getting output as : eg. dblSlabResult = 1002.1
To represent use formatting. In your case exactly two digits after decimal point means "F2" format string
double source = 1234.56789;
// 1234.57
var result = source.ToString("F2");
Very simple. Try this
public double UptoTwoDecimalPoints(double num)
{
var totalCost = Convert.ToDouble(String.Format("{0:0.00}", num));
return totalCost;
}
The # character is an optional digit placeholder. Use 0 to enforce digits when converting to string:
string.Format("{0:#.##}", 1002.1) == "1002.1"
string.Format("{0:0.00}", 1002.1) == "1002.10"
Don't expect a specific count of digits when rounding float or double. They are just numbers, independent of their string format.
What inputs are you using? Math.Round should be working correctly, which suggests that the line above is returning a double with only 1 significant figure.

Converting String to Double from ListBox to TextBox

// Calculating and diplaying pricing in list.
for (double MAX = 4.25; MAX >= MIN; MAX -= 0.05)
{
Price = (X * MAX);
prices = Price.ToString("c");
listFinances.Items.Add(prices);
}
---
private void listFinances_SelectedIndexChanged(object sender, EventArgs e)
{
string TotalPrice = listFinances.SelectedItem.ToString();
double stateIncentive = (Convert.ToDouble(TotalPrice) / 4);
txtStateTax.Text = stateIncentive.ToString();
}
So I'm trying to take a ListBox of string currency values, turn them into a double, divide them by 4, and display the result in a TextBox. The user will select the ListBox value and the program should automatically divide by 4 and display.
It's not working however. The program always does an exception throw when you click the ListBox item. The exception is thrown at:
double stateIncentive = (Convert.ToDouble(TPrice) / 4);
saying that:
It's not in the correct format.
Can someone help me out here?
You add your strings with the currency symbol. If you want to parse the string back to a double (but it is better use a decimal) you need to tell the conversion that you have that symbol and ignore it
private void listFinances_SelectedIndexChanged(object sender, EventArgs e)
{
string TotalPrice = listFinances.SelectedItem.ToString();
decimal stateIncentive = decimal.Parse(TotalPrice, NumberStyles.Currency, CultureInfo.CurrentCulture) / 4);
txtStateTax.Text = stateIncentive.ToString();
}
I have used decimal instead of double because the decimal type is more adapt to handle money values. I suggest to make the same change in the for..loop that fill the list (Just use the suffix m to specify constant decimal values (IE. 4.25m and 0.05m)
You are trying to convert a currency string to double so you should Try like this:
double stateIncentive = (Double.Parse(TotalPrice, System.Globalization.NumberStyles.Currency) / 4);
Or would be better if using decimal (Read this to know why):
decimal stateIncentive = (decimal.Parse(TotalPrice, System.Globalization.NumberStyles.Currency) / 4);
The style parameter defines the style elements (such as white space, thousands separators, and currency symbols) refer to MSDN:Double.Parse Method (String, NumberStyles)

Dataset adding values by decimal but returning 0

I have a data-set with 2 columns.
I'm adding the 2 values together, both are object(decimal) types.
private decimal CalculateCensusForChild(DataSet dsGADCensusDetails)
{
var total = 0.00M;
foreach (DataRow dr in dsGADCensusDetails.Tables[0].Rows)
{
total += WebUtility.Cast(dr["Male"], 0.00M) + WebUtility.Cast(dr["Female"], 0.00M);
}
return total;
}
public static decimal Cast(Object aValue, decimal aOnError)
{
decimal result;
try
{
result = decimal.Parse(aValue.ToString());
}
catch
{
result = aOnError;
}
return result;
}
The total returns fine when the values are whole int numbers but I'm looking for them to be decimal values and thus return a decimal value which I will later turn into a string with no decimal places.
e.g 0.65 + 0.25 returns 0.
The total will always equal a whole number but it's required on the UI to show decimal values to reduce rounding, so bit of workaround that may seem unnecessary but that's the world we live in.
So I think I'm messing up on syntax to convert it to a decimal while it's adding but any other ideas are very welcomed.
Cheers folks.

Digit grouping with two decimal places in c#

I want to display a number which is of double datatype in C#, in grouped digits and with two decimal places only if it contains a decimal no.
e.g. If there is 2000.4567 and 2000.45, it must be displayed as 2,000.45 and if it is 2000 then it will displayed as 2,000 (grouped but without decimal).
I have tried this and it is working fine for digit grouping but it rounds off the decimal no. to an integer value either by floor or ceil:
DimensionLength.ToString("#,##0")
DimensionLength is of type double.
Try this Code
double s=123.345345;
string str=string.Empty;
str = s.ToString("#,0.##");
MessageBox.Show(str);
I think you are better off by creating your own custom condition
double _inputval=2000.4567
string _outputVal="";
if ((_inputval % 1) == 0)
{
_outputVal = _inputval.ToString("#,##");
}
else
{
_outputVal = _inputval.ToString("N2");
}
Hope it helps

Categories