Kelvin B
Kelvin B

Reputation: 33

How to +/add text together to get total C#

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.

Upvotes: 0

Views: 57

Answers (4)

Martin Ekman
Martin Ekman

Reputation: 1

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

Upvotes: 0

Heinzi
Heinzi

Reputation: 172220

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:

  1. 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.
  2. Add your numbers.
  3. 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).

Upvotes: 3

zbigniewcebula
zbigniewcebula

Reputation: 1651

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

Upvotes: -1

godot
godot

Reputation: 3545

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()

Upvotes: 0

Related Questions