now I have 3 textboxes that the user can type in them his degrees and the average will be calculated and displayed in another textbox! I've made the result to show just two fractional digits by calling the Math.Round() Method
This is my code:
double Sum = int.Parse(textBox1.Text) + int.Parse(textBox2.Text) + int.Parse(textBox3.Text);
double Avg = Sum / 3;
textBox4.Text = Math.Round(Avg, 2).ToString();
My problem is whenever the average is equal to an integer number like 20, I want it to display 20.00
Since C# 6.0 you can use string interpolation to format variables into a string (in this case, format the number with two decimal places):
$"{Avg:.00}"
Alternatively, use string#Format:
string.Format("{0:.00}", Avg);
If you don't want to use either of those, you can use the ToString function with this parameter for that as mentioned in the comments:
Avg.ToString("0.00")
Related
here is what I'm trying to do:
double result = Math.Pow((1 + 8), 60) - 1;
And the result variable is:
1.7970102999144311E+57 double
And trying to:
Math.Round(result, 5);
Returns same : 1.7970102999144311E+57 double
I'd like to round it to 1.79701 for example
Any solutions ?
You're misunderstanding what you're seeing.
1.7970102999144311E+57
Is scientific notation for
1797010299914431100000... (with 41 trailing zeros).
It is a whole number, thus rounding it to 5 decimal places will correctly return the same value.
What you want to do is format the output of the number
String.Format(CultureInfo.InvariantCulture, "{0:0.#####E+0}", result);
Which returns 1.79701E+57. Note that this is a very different number from 1.79701
The problem you're having is that Math.Round rounds things to the right of the decimal point. For example if you're dealing with currency and you perform an operation that leaves you with $1.5234524, you would use:
Math.Round(1.5234524,2);
// output 1.52
The number you're dealing with is actually scientific notation for a very large number with nothing to the right of the decimal point. This is why the result of Math.Round is the same as the input.
The earlier comments and answers are correct. But to get what you are trying to achieve you can use the following:
double result = Math.Pow((1 + 8), 60) - 1;
string s = String.Format("{0:E5}", result);
double d = Double.Parse(s);
I have been searching forever and I simply cannot find the answer, none of them will work properly.
I want to turn a double like 0.33333333333 into 0,33 or 0.6666666666 into 0,66
Number like 0.9999999999 should become 1 though.
I tried various methods like
value.ToString("##.##", System.Globalization.CultureInfo.InvariantCulture)
It just returns garbage or rounds the number wrongly.
Any help please?
Basically every number is divided by 9, then it needs to be displayed with 2 decimal places without any rounding.
I have found a nice function that seems to work well with numbers up to 9.999999999
Beyond that it starts to lose one decimal number. With a number like 200.33333333333
its going to just display 200 instead of 200,33. Any fix for that guys?
Here it is:
string Truncate(double value, int precision)
{
string result = value.ToString();
int dot = result.IndexOf(',');
if (dot < 0)
{
return result;
}
int newLength = dot + precision + 1;
if (newLength == dot + 1)
{
newLength--;
}
if (newLength > result.Length)
{
newLength = result.Length;
}
return result.Substring(0, newLength);
}
Have you tried
Math.Round(0.33333333333, 2);
Update*
If you don't want the decimal rounded another thing you can do is change the double to a string and then get get a substring to two decimal places and convert it back to a double.
doubleString = double.toString();
if(doubleString.IndexOf(',') > -1)
{
doubleString = doubleString.Substring(0,doubleString.IndexOf(',')+3);
}
double = Convert.ToDouble(doubleString);
You can use a if statement to check for .99 and change it to 1 for that case.
Math.Truncate(value * 100)/100
Although I make no guarantees about how the division will affect the floating point number. Decimal numbers can often not be represented exactly in floating point, because they are stored as base 2, not base 10, so if you want to guarantee reliability, use a decimal, not a double.
Math.Round((decimal)number, 2)
Casting to a decimal first will avoid the precision issues discussed on the documentation page.
Math.Floor effectively drops anything after the decimal point. If you want to save two digits, do the glitch operation - multiply then divide:
Math.Floor(100 * number) / 100
This is faster and safer than doing a culture-dependent search for a comma in a double-converted-to-string, as accepted answer suggests.
you can try one from below.there are many way for this.
1.
value=Math.Round(123.4567, 2, MidpointRounding.AwayFromZero) //"123.46"
2.
inputvalue=Math.Round(123.4567, 2) //"123.46"
3.
String.Format("{0:0.00}", 123.4567); // "123.46"
4.
string.Format("{0:F2}", 123.456789); //123.46
string.Format("{0:F3}", 123.456789); //123.457
string.Format("{0:F4}", 123.456789); //123.4568
I'm trying convert a decimal into integer and want to round the value up or down depending on the situation.
Basically example is:
12/3 = 4 so should round to 4
11/3 = 3.66666 so should round to 4
10/3 = 3 = 3.33333 so should round to 3
9/3 = 3 so should round to 3
Whatever I found on the internet always rounds down or always rounds up, never makes a judgment call based on the numbers.
If x is the number you want to round and you want the "normal" rounding behavior (so that .5 always gets rounded up), you need to use Math.Round(x, MidpointRounding.AwayFromZero). Note that if you are actually computing fractions and the numerator and denominator are integers, you need to cast one of them to double first (otherwise, the division operator will produce an integer that is rounded down), and that if you want the result to be an int, you need to cast the result of Round():
int a = 5;
int b = 2;
double answer = (int) Math.Round(a / (double) b, MidpointRounding.AwayFromZero);
Math.Round(value) should do what you want. Examples console app code to demonstrate:
Console.Write("12 / 3 = ");
Console.WriteLine((int)Math.Round(12d / 3d));
Console.WriteLine();
Console.Write("11 / 3 = ");
Console.WriteLine((int)Math.Round(11d / 3d));
Console.WriteLine();
Console.Write("10 / 3 = ");
Console.WriteLine((int)Math.Round(10d / 3d));
Console.WriteLine();
Console.Write("9 / 3 = ");
Console.WriteLine((int)Math.Round(9d / 3d));
Console.WriteLine();
Console.ReadKey();
Does Math.Round(d) do what you require?
Return Value:
The integer nearest parameter d. If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned. Note that this method returns a Decimal instead of an integral type.
Check out the Round reference page
You could try this
Math.Round(d, 0, MidpointRounding.AwayFromZero)
Sometime, people add 0.5 to the number before converting to int.
string input = Console.ReadLine();
decimal sum = Convert.ToDecimal(input);
if (sum >= (decimal)500.01)
{
//40% and 8 dollars off shipping costs are taken off total amount
decimal totalprice;
totalprice = (sum - 8) * .60m;
Math.Truncate(totalprice);
Console.WriteLine("Your final cost is:${0:0.00}", totalprice);
Console.Read();
The problem is, when I enter the price 598.88 dollars into my program, I should get 354.52.
The Math:
598.88 - 8 = 590.88. 590.88 * 60% = 354.528
I actually get 354.53 because C# rounds up instead of down.
For example,
If I get an answer like 519.998, I want it to STAY at 519.99.
Another example, if I get an answer like 930.755 I want it to stay at 930.75.
I looked into some answers, but Math.Truncate obviously doesn't work for me and using the *100 / 100 trick didn't work either. Keep in mind I'm a new student, So, if an answer could be noob-safe, that would be nice. Thanks.
The * 100 / 100 works fine, you might have been using it wrong. Try this below:
decimal totalprice = TruncateToTwoDigits((sum - 8) * .60m);
Console.WriteLine("Your final cost is:${0:0.00}", totalprice);
...
private static decimal TruncateToTwoDigits(decimal Value)
{
int adjusted = (int)Math.Truncate(Value * 100m);
return adjusted / 100m;
}
As a side note, Math.Truncate returns the truncated value, it doesn't change the input parameter as your code would imply.
Math.Truncate like all the other Math function returns the value after the function is called. The function doesn't alter your variable. Actually this was not possible with doubles (please see ref parameters). So you need to do:
totalprice = Math.Truncate(totalprice);
please notice that totalprice will have just the integer part so if the value is 45.985 the result is 45 so you need to multiply by 100 and then divide. http://msdn.microsoft.com/en-us/library/7d101hyf.aspx
The rounding up that you get there is because console.Write calls String.Format that will do that. See http://www.csharp-examples.net/string-format-double/ to get your write function call.
Modulo works too. (It's hard to say which is better for safety, readability, and performance.)
Decimal totalprice = (sum - 8m) * 0.60m; // Discount $8.00 and then 40%.
totalprice -= totalprice % 0.01; // Truncate to two decimal places.
Similar question at Truncate Two decimal places without rounding
Say I have a double variable initialized as
double dValue = 5.156365
I would like to show this in a textbox as 5.16 i.e only two decimal places.
How should I format?
Is textbox.Text = dValue.ToString("F2", Culture.....) correct? When I tried it did give me the correct result. However, if dValue = 5 then I would like only 5 to be shown and not 5.00.
How could I achieve this in C#?
A 0 in the string forces that decimal place, while a # lets the number get up to that decimal place.
dValue.ToString("0.##")