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
I need to display a number with commas and a decimal point.
Eg:
Case 1 : Decimal number is 432324 (This does not have commas or decimal points).
Need to display it as: 432,324.00.
Not: 432,324
Case 2 : Decimal number is 2222222.22 (This does not have commas).
Need to display it as: 2,222,222.22
I tried ToString("#,##0.##"), but it is not formatting it correctly.
int number = 1234567890;
number.ToString("#,##0.00");
You will get the result 1,234,567,890.00.
Maybe you simply want the standard format string "N", as in
number.ToString("N")
It will use thousand separators, and a fixed number of fractional decimals. The symbol for thousands separators and the symbol for the decimal point depend on the format provider (typically CultureInfo) you use, as does the number of decimals (which will normally by 2, as you require).
If the format provider specifies a different number of decimals, and if you don't want to change the format provider, you can give the number of decimals after the N, as in .ToString("N2").
Edit: The sizes of the groups between the commas are governed by the
CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes
array, given that you don't specify a special format provider.
Try with
ToString("#,##0.00")
From MSDN
*The "0" custom format specifier serves as a zero-placeholder symbol. If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string. The position of the leftmost zero before the decimal point and the rightmost zero after the decimal point determines the range of digits that are always present in the result string.
The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.*
I had the same problem. I wanted to format numbers like the "General" format in spreadsheets, meaning show decimals if they're significant, but chop them off if not. In other words:
1234.56 => 1,234.56
1234 => 1,234
It needs to support a maximum number of places after the decimal, but don't put trailing zeros or dots if not required, and of course, it needs to be culture friendly. I never really figured out a clean way to do it using String.Format alone, but a combination of String.Format and Regex.Replace with some culture help from NumberFormatInfo.CurrentInfo did the job (LinqPad C# Program).
string FormatNumber<T>(T number, int maxDecimals = 4) {
return Regex.Replace(String.Format("{0:n" + maxDecimals + "}", number),
#"[" + System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + "]?0+$", "");
}
void Main(){
foreach (var test in new[] { 123, 1234, 1234.56, 123456.789, 1234.56789123 } )
Console.WriteLine(test + " = " + FormatNumber(test));
}
Produces:
123 = 123
1234 = 1,234
1234.56 = 1,234.56
123456.789 = 123,456.789
1234.56789123 = 1,234.5679
Try with
ToString("#,##0.###")
Produces:
1234.55678 => 1,234.556
1234 => 1,234
For Razor View:
$#string.Format("{0:#,0.00}",item.TotalAmount)
CultureInfo us = new CultureInfo("en-US");
TotalAmount.ToString("N", us)
Your question is not very clear but this should achieve what you are trying to do:
decimal numericValue = 3494309432324.00m;
string formatted = numericValue.ToString("#,##0.00");
Then formatted will contain: 3,494,309,432,324.00
All that is needed is "#,0.00", c# does the rest.
Num.ToString("#,0.00"")
The "#,0" formats the thousand separators
"0.00" forces two decimal points
If you are using string variables you can format the string directly using a : then specify the format (e.g. N0, P2, etc).
decimal Number = 2000.55512016465m;
$"{Number:N}" #Outputs 2,000.55512016465
You can also specify the number of decimal places to show by adding a number to the end like
$"{Number:N1}" #Outputs 2,000.5
$"{Number:N2}" #Outputs 2,000.55
$"{Number:N3}" #Outputs 2,000.555
$"{Number:N4}" #Outputs 2,000.5551
string Mynewcurrency = DisplayIndianCurrency("7743450.00");
private string DisplayIndianCurrency(string EXruppesformate)
{
string fare = EXruppesformate;
decimal parsed = decimal.Parse(fare, CultureInfo.InvariantCulture);
CultureInfo hindi = new CultureInfo("en-IN");
// string text = string.Format(hindi, "{0:c}", parsed);if you want <b>Rs 77,43,450.00</b>
string text = string.Format(hindi, "{0:N}", parsed); //if you want <b>77,43,450.00</b>
return ruppesformate = text;
}
For anyone looking at this now, and getting the "No overload for method 'ToString' takes 1 argument" when using:
TotalNumber.ToString("N")
My solution has been to use :
TotalNumber.Value.ToString("N")
I often get stuck on this when working directly inside an MVC View, the following wasn't working:
#Model.Sum(x => x.Number).ToString("N")
Whereas this works:
#Model.Sum(x => x.Number).Value.ToString("N")
I'm having an issue after submitting a form with the following error:
Input string was not in a correct format.
My code:
Decimal intervalStart = Decimal.Parse(IntervalTime.Text);
Decimal intervalTotal = intervalStart * 1000;
string interval = intervalTotal.ToString();
I am trying to get a total in whole number rather than decimal, but the decimal is crucial in order to get that whole number (when multiplied by 1000).
For example, my small application reads a video file and puts the total in seconds in the "IntervalTime.Text" box. This is then converted into milliseconds and becomes a whole number.
Video: 87.524 seconds. Multiply it by 1000, you get 87524. <- This is what I need but continue getting the above error.
The Decimal.Parse(String) parse the number which is in this format:
[ws][sign][digits,]digits[.fractional-digits][ws]
Be carefull that
, is a culture-specific thousands separator symbol.
. is a culture-specific decimal point symbol
This means that both 87,524 and 87.524 could be valid decimal number strings depending on the system culture.
This doesn't work:
string b = "87.524";
Decimal intervalStart2 = Decimal.Parse(a);
But this does:
string a = "87,524";
Decimal intervalStart1 = Decimal.Parse(a);
Problem is in delimiter.
One of possible solutions could be:
string b = "87.524";
b = b.Replace(".", ",");
Decimal intervalStart = Decimal.Parse(b);
Also in this question it is shown how to define delimiter yourself:
decimal.Parse("87.524", new NumberFormatInfo() { NumberDecimalSeparator = "." })
Another way is to define specific CultureInfo:
decimal.Parse("87.524", new CultureInfo("en-US"));
i got string values representing doubles. (f.e. "1.23"). Always with ".".
If you run the code:
double dDouble =0;
string sDemo ="1.23";
double.TryParse(sDemo,out dDouble));
it will return 1.23 to the dDouble var.
If i switch to a different languge with "," as "." .... i get 123.0 as dDouble.
How do I ensure that its always 1.23 ...
double dDouble =0;
string sDemo ="1.23";
double.TryParse(sDemo,System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out dDouble));
but I am unsure, if this will solve the problem permanently.
i just tried
10 years ago I would solve it like this (do not do that):
sDemo = sDemo.Replace(",",".");
Now
// to string
var text = someDouble.ToString(NumberFormatInfo.InvariantInfo);
// and back
var number = double.Parse(text, NumberFormatInfo.InvariantInfo);
Key point is to use same culture. If you convert values for internal use (to example, passing double value as a part of text) - use invariant culture. If, however, you want to display it to the user and then read user input, then still use same culture: if you don't specify culture for ToString, then don't specify it for Parse, and if you did, then do it again.
I am getting the following values from database:
99, 12, 12.2222, 54.98, 56, 17.556
Now I want to show that values like below:
99%, 12%, 12.22% , 54.98% , 56%, 17.55%
Please give me any suggestion to acchive this.
Its very easy in C#:
[EDIT]
var val = 99.569;
string result = string.Format("{0:0.##}%", val);
You can take a look for Format method of string class:
http://msdn.microsoft.com/en-us/library/fht0f5be.aspx
and I recomend you to take a look on custom format strings:
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
Use the ToString method that takes a string format - the format you want is "P2" or the custom format #0.##%. Both of these formatting options multiply by 100, expecting your data to be in standard percent format so you will need to divide to accomadate and use it.
To use ToString without the divide you can use "#0.##\%" which will format the numeric part and include the percent sign as a literl, this is the equivilent for ToString as the format from Anton Semenov's answer using the string.Format function on this thread.
Msdn article - Standard Formats
Msdn article - Custom Formats
to formart 12.2222 use f
string.Format("{0:f}%", 12.2222); //output 12,22%
Try this Out
List<double> myList = new List<double>();
myList.Add(0.1234);
myList.Add(99);
myList.Add(12.1234);
myList.Add(54.98);
foreach (double d in myList)
{
string First = string.Format("{0:0.00%}", d); //Multiply value by 100
Console.WriteLine(First);
string Second = string.Format("{0:P}", d);//Multiply value by 100
Console.WriteLine(Second);
string Third = string.Format("{0:P}%", d.ToString());//Use this One
Console.WriteLine(Third);
string Four = d.ToString() + "%"; //Not a good idea but works
Console.WriteLine(Four);
Console.WriteLine("=====================");
}
Console.ReadLine();
I have made a little trick here {0:P} will multiply your given value by 100 and then show it but you just want to place a % sign after value so first convert the given value to TOString than apply {0:p}
If you want to specify the number of decimal places to 2 (ie. not 12.2222%, but 12.22%), then use:
val.ToString("0.00") + "%"
Note that this will round the number off, so 12.226 would be shown as 12.23%, etc.