I just started programming C# today, and I'm trying to get a handle on the format strings.
I would like to output a string of this format:
{decimal number using a maximum of 10 columns} +
" " +
{decimal number taking a maximum of 10 columns}
I've tried
String outputFormat = "{0,-10:0.#####} {1,-10:0.#####}";
String output = String.Format(outputFormat, x, y);
But if x is 34059834.340598, I don't get the output I want.
The first number takes more than 10 columns.
Is there a format string to force numbers to 10 columns? (Maybe show E notation if the n.m would be greater than 10 columns).
I think you are looking for the G specifier for you number formating.
Something like this (untested) should work:
string tenCols = myDecimal.ToString("G10");
Or to be more inline with what you had before, I think this should do it:
String outputFormat = "{0,-10:G10} {1,-10:G10}";
String output = String.Format(outputFormat, x, y);
double x = 34059834.340598
string displayX = x.ToString().Substring(0,10);
I'm pretty sure you won't be able to do what you want using format strings directly, but it's easy enough with string manipulation in code.
Related
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'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 want to read a string, get a specific number from the string, multiply this by a double and replace the old by the new string-number.
After the multiplication, the format of the number changes
Example: original format 8.08000e+14
Multiplication by, lets say two, returns: 1.616E+15
I want the new number to have exactly the format of the old number (would be 1.61600e+15, could be done for instance using String.Format), but for doing so, I need to get the format of the old number first (this format is not always the same). How can I get this format info?
Here is a rather hacky approach:
Assuming that your original format is in the e-notation. You could find the amount of digits between the . and e Then use the number for the transformation again into the e-notation.
Here is a small example:
string test = "4.08123000E+14";
//string test = "8.08000e+14";
double test_as_double = Convert.ToDouble(test);
test_as_double *= 2.0;
// find all digits between . and e or E
string old_format = System.Text.RegularExpressions.Regex.Match(test, #".\d+[e|E]").Value;
// take the amount of digits without the . and e
int number_of_digits = old_format.Length-2;
// create the new number-string with the old folmar
string new_old_Format = test_as_double.ToString("E" + number_of_digits.ToString(), CultureInfo.InvariantCulture);
I need to convert some value into decimal. i have done with the below:
Double calculateinputPower="somegivenvalue";
String valuePower="somevalue";
Double calculatePower = Double.Parse(valuePower);
calculatePower = calculatePower - calculateinputPower + calculateErp * 1;
calculatePower = Double.Parse(String.Format("{0:0.0}", calculatePower));
valuePower = System.Convert.ToString(calculatePower);
ERP.Text = valuePower;
if my output value is like
ex:66.2356 -> 66.2 , 32.568 -> 32.5 , 22.35264 ->22.3
i am getting the format which i need exactly but if the output value is like
22,33,11,66,55 something like this then i want convert that value to
22->22.0
33->33.0
11->11.0
66->66.0 how can i get this in C#.
i used myVal.ToString("F"); then i am getting 0.00
if i use ToString("N2"); then i am getting 1,000.00
but i don't want money format or 0.00 format
What exactly i need is single .0 if the value is non decimal.
Just use .ToString("0.0") (Note this uses rounding so 22.26 -> 22.3)
double i = 22.23;
double j = 45;
string si = i.ToString("0.0"); //22.2
string sj = j.ToString("0.0"); //45.0
Try in this way:
valuePower = calculatePower.ToString("F1");
To learn more, follow this link
You need to look at the documentation for the format strings you're using.
You've tried F, which says as you've not specified the precision that the "Default precision specifier: Defined by NumberFormatInfo.NumberDecimalDigits.", which is 2 in your case.
You've tried N2, which says that the 2 is the "Precision specifier: Desired number of decimal places.".
As you only want a single decimal place, use F1 or N1, depending on your formatting requirements.
var number1 = 66.2356d;
var number2 = 66d;
var string1 = number1.ToString("N1"); // 66.2
var string2 = number2.ToString("N1"); // 66.0
See this fiddle.
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.