I have basically two text which I would like to plus together to get a total.
What I need this to do is :
price.Text = 50.50
addprice.Text = 140.50
price.Text + addprice.Text
to get : 191.00
I tried looking everywhere to find how to get this working, Any ideas/suggestions. Much Appreciated.
You cannot perform mathematical operations on strings directly, you need to use a numeric data type for that.
Let's do this step by step:
Convert your texts to numbers. You can use Decimal.TryParse for that. Think about what you want to happen if the text does not contain a valid number.
Add your numbers.
Convert your sum back to text. You can use Decimal.ToString for that.
Implementation is left as an exercise, but the SO crowd will surely help you if you get stuck.
Note: Since your numbers seem to be monetary values, you should use decimal rather than double or float).
var total = Convert.ToDecimal(price.Text) + Convert.ToDecimal(addPrice.Text);
Convert your strings to decimal then sum and if you want to convert back to string just: total.ToString()
As string:
string total = (decimal.Parse(price.Text) + decimal.Parse(addPrice.Text)).ToString();
or as decimal:
decimal total = decimal.Parse(price.Text) + decimal.Parse(addPrice.Text);
You need to parse those texts into a numbers (floats in this case).
float priceNumber = 0;
float addPriceNumber = 0;
if(float.TryParse(price.Text, out priceNumber) && float.TryParse(addprice.Text, out addPriceNumber )) {
//Here, the priceNumber and addPriceNumber has numbers stored as float
float result = priceNumber + addPriceNumber;
} else {
//Error parsing, wrong format of numbers
}
Docs: float.TryParse / Single.TryParse
Some knowledge about parsing: Wiki
Related
I have a label (lblAmountTendered) which contains Currency String in it. I would like to convert it into double to perform some calculation. However, it shown an Error Message: Input string was not in a correct format in the first statement.
Here is my code:
double balance = double.Parse(amount) - double.Parse(lblAmountTendered.Text.ToString());
lblBalanceDue.Text = balance.ToString("c2",CultureInfo.CreateSpecificCulture("en-MY"));
For Example:
lblAmountTendered = RM 15
I want to retrieve the value of it (15) for calculation.
Looking forward for the solution. I appreciate for your help! :)
PROBLEM SOLVED
lblAmountTendered.Text.ToString().Remove(0,3)
Remove(0,3) helps us to remove 'RM' from 'RM 15', so we can convert it to double or float easily as shown in below:
float.Parse(lblAmountTendered.Text.ToString().Remove(0, 3))
Here you first need to retrieve the numeric value from a string using below regex:
string resultNum = Regex.Match(lblAmountTendered.Text, #"\d+").Value;
and then use resultNum in your code like-
double balance = double.Parse(amount.ToString()) - double.Parse(resultNum);
lblBalanceDue.Text = balance.ToString("c2",CultureInfo.CreateSpecificCulture("en-MY"));
Im having alot of problems trying to take out the decimal part of my string,
the string comes from a var type in my view like this:
var temp = dashList[index];
#PrintSection(actualDate, Model, String.Format("{0:0.000}", temp.Rubro))**
temp.Rubro is my String part that can be ".00" or ".XX"
however i need to take the decimal part of the string only when its value is ".00"
since i have some values of the dashlist have important decimal parts.
Is there a way to take the decimal part of a string only if it equals to ".00"???
The output im trying to get is:
From XX.00 -> XX
From XX.12 -> XX.12
both kinds are on my list
Try this:
var temp = dashList[index];
#PrintSection(actualDate, Model, String.Format("{0:0.000}", temp.Rubro).Replace(".00", ""))
You can try using
String.Format("{0:G29}", decimal.Parse(temp.Rubro)))
Whereas all the below formats achieve the same results.
string.Format("{0:G29}", decimal.Parse("2.00"))
decimal.Parse("2.00").ToString("G29")
2.0m.ToString("G29")
You can use ToString() with the General ("G") Format Specifier to achieve the desired result. Trailing zeros are truncated when using this format string with a precision specified. In order to prevent rounding in any situations, you will need to set the precision to the maximum allowed for decimals (29).
Simple trick...
You can parse the string and it will automatically remove the decimal places
try following
private static void ParseDouble()
{
string sDouble = "12.00";
double dValue = double.Parse(sDouble);
Console.WriteLine(dValue.ToString());
sDouble = "12.14";
dValue = double.Parse(sDouble);
Console.WriteLine(dValue.ToString());
}
Your output will be
12
12.14
Hope this helps.
I will suggest you to use accounting.js plugging which is pretty straightforward. I have used it in some projects and as of today I cannot complain. Otherwise, you could do something like this,
var x = temp.Replace(".00","").Trim();
I have to round decimal value into 6 decimal places in C#. When i use sum of 0.046080 and 0.116220 with below code segment answer is 0.1623
DesTot = Math.Round(TotalQty + sumtot, 6);
But i want to display the answer as 0.162300
How can i do it with C#
You need to display it using ToString using the format you wish.
Something like
DesTot.ToString("0.000000")
Try format your out put display like the following
// this code always round number to 4 places and adds two zeros at the end.
double TotalQty = 0.116220;
var DesTot= Math.Round(TotalQty, 4).ToString("0.000000");
Console.Write(DesTot);
In case of your code it will be
var DesTot = Math.Round(TotalQty + sumtot, 6).ToString("0.000000");
I need help converting a string to double with 7 decimals. I have a string "00000827700000" and need it converted to 82.77
Tried using String.Format() with {0:N7} without success.
It looks like you could use:
decimal x = decimal.Parse(text.Substring(0, 7) + "." +
text.Substring(7),
CultureInfo.InvariantCulture);
That would actually parse it to 82.7700000, as decimal preserves trailing zeroes (to an extent) but maybe that's good enough? It not, you could change the second argument to
text.Substring(7).TrimEnd('0')
Note that I'd strongly recommend you to at least consider using decimal instead of double. You haven't explained what this value represents, but if it's stored as decimal figures which you need to preserve, it smells more like a decimal to me.
Based on the edit, it could be simplified as
var text = "00000827700000";
var x = decimal.Parse(text, CultureInfo.InvariantCulture) / 10000000;
Console.Write(String.Format("{0:N7}", x));
I have a number like so: 4.47778E+11
Can anyone give me a way of converting that into its number representation easily in c#?
Thanks
string s = "4.47778e+11";
double d = double.Parse(s);
or
string s = "4.47778e+11";
if (double.TryParse(s,out d))
{
// number was parsed correctly
}
or for internationalization
double.Parse("4.47778e+11", System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);
Try this MSDN thread. It's called scientific notation by the way, and a quick google normally solves simple issues.
That's assuming you mean parsing from a string to a float, your question & title are conflicting
Use
float num = Convert.ToFloat(Convert.ToDouble(s));
But you still lose precision, floats are only precise to 7 digits, so you're better off using just the Convert.ToDouble() (precise to 15 or so digits), so you won't lose any digits in your example.
Use Convert:
double value = Convert.ToDouble("4.47778E+11");