Sum of two double numbers [duplicate] - c#

This question already has answers here:
How do I parse a string with a decimal point to a double?
(19 answers)
Closed 2 years ago.
Console.Write("First Number: ");
double n1 = double.Parse(Console.ReadLine());
Console.Write("Second Number: ");
double n2 = double.Parse(Console.ReadLine());
double r = n1+n2;
Console.WriteLine($"The result r are {r}");
When I input, for example:
2.3 and 5.2, the output is that r equals to 23 + 52 = 75, and not 7.5.
Why?

What version of .NET framework are you using? Example you gave works fine when run on .NET 5.
What crossed my mind is that the runtime takes localization into account and doesn't look for . as decimal point and ignores it instead. Maybe it looks for ,.
What you can try is passing some other localization setting to a parser like so
double.TryParse(Console.ReadLine(), NumberStyles.Number, CultureInfo.CreateSpecificCulture ("en-US"), out temp)
This should work with ..

Related

Problems with formatting decimals in c# [duplicate]

This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 8 months ago.
I'm trying to create a simple C# program (I'm a beginner) to convert days to weeks, months and years. However, the answer always appears in integers, not decimals. For example: 1200 days are equivalent to 3.2876 years, but the program returns only 3. I am using VSCode and .NET 6.0. I tried some output formatting but only got 3.00. Here is the code:
static void Main(string[] args)
{
string aux="";
int daysEntrada=0;
decimal monthSaida, yearsSaida, weeksSaida;
Console.WriteLine("-----------------------------");
Console.WriteLine("days conversor!");
Console.Write("Enter the number of days: ");
Console.WriteLine("\n-----------------------------");
Console.Write("-> ");
aux = Console.ReadLine();
bool isInteiro = int.TryParse(aux, out daysEntrada);
if(isInteiro == true){
daysEntrada = int.Parse(aux);
monthSaida = daysEntrada/30;
yearsSaida = daysEntrada/365;
weeksSaida = daysEntrada/7;
Console.WriteLine($"{daysEntrada} days is equal to: {daysEntrada} days, {weeksSaida} weeks, {monthSaida} months ans {yearsSaida} years.");
}else{
Console.WriteLine("Error, type again.");
}
}
The output generates:
days conversor!
Enter the number of days:
-----------------------------
-> 1200
1200 days is equal to: 1.200,00 days, 171 weeks, 40 months ans 3,00 years
The following is a rule that is valid in C, C++, C# and many more:
Division of two integers gives an integer so when you divide daysEntrada by 365 it returns the floor of the division( for example if it is 3.2876 it returns 3 if it's 3.99 it returns 3).
The solution in C# is to cast any of the values to decimal, I'm no expert in C# but this might work:
yearsSaida = daysEntrada/(decimal)365;
Also an useful article:
How can I divide two integers to get a double?
Try using floats instead of ints and decimals. The original error was caused because your original data type was int so when you divided it it returned an int (non decimal). Here I used floats for all the data types as that way you don't have to cast any values (from int to decimal).
Like this (changes were commented):
public static void Main(string[] args)
{
string aux="";
float daysEntrada=0; // changed from int to float
float monthSaida, yearsSaida, weeksSaida; // changed from decimal to float
Console.WriteLine("-----------------------------");
Console.WriteLine("days conversor!");
Console.Write("Enter the number of days: ");
Console.WriteLine("\n-----------------------------");
Console.Write("-> ");
aux = Console.ReadLine();
bool isInteiro = float.TryParse(aux, out daysEntrada); // changed from int.tryparse to float.tryparse
if(isInteiro == true){
daysEntrada = float.Parse(aux); //changed from int to float
monthSaida = daysEntrada/30;
yearsSaida = daysEntrada/365;
weeksSaida = daysEntrada/7;
Console.WriteLine($"{daysEntrada} days is equal to: {daysEntrada} days, {weeksSaida} weeks, {monthSaida} months ans {yearsSaida} years.");
}else{
Console.WriteLine("Error, type again.");
}
}

Why are results rounding down ? (C#) [duplicate]

This question already has answers here:
How can I divide two integers to get a double?
(9 answers)
Closed last year.
I'm a beginner trying to make a very basic calculator.
I have a problem with division, though;
For some reasons, the result is always rounded down not matter what:
Console.WriteLine("First Argument ?");
int Arg1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second argument ?");```
int Arg2 = Convert.ToInt32(Console.ReadLine());
float OpDiv = Arg1 / Arg2;
Console.WriteLine($"The result is {OpDiv}");
For example here, 11 / 3 returns 3, instead of 3.66666666...
What have I done wrong ???
Change to:
Console.WriteLine("First Argument ?");
int Arg1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second argument ?");
int Arg2 = Convert.ToInt32(Console.ReadLine());
float OpDiv = (float)Arg1 / Arg2;
Console.WriteLine($"The result is {OpDiv}");

(C#) I'm having trouble with the Convert function in regard to strings

I'm very new to programming and I wanted to create a small console app that calculates Force when given 2 charges and the distance between them according to Coulomb's Law.
I seem to be having a problem with converting strings to decimals.
I'm not quite sure how to multiply multiple stings( Q1, Q2 and r)
This is an image of my code along with the console display and error message.
Console.WriteLine("Welcome to Dieter's Coulomb's Law Calculator!");
Console.WriteLine("Press Enter to continue.");
String Q1;
String Q2;
String r;
Decimal k = (9 * 10 ^ 9);
Console.ReadLine();
Console.WriteLine("All you need to do is insert the first charge, the second chage and the distance between them.");
Console.WriteLine("Remember to give your values in coulombs and meters.");
Console.WriteLine("Charge 1: ");
Q1 = (Console.ReadLine());
Console.WriteLine("Charge 2: ");
Q2 = Convert.ToString(Console.ReadLine());
Console.WriteLine("Distance in m: ");
r = Convert.ToString(Console.ReadLine());
Console.WriteLine(" Equation: k*|Q1*Q2|/r^2");
Console.WriteLine("Equation: " + "9*10^9*" + "|" + Q1 + "*" + Q2 + "|" + "/" + r + "^2" );
Decimal ans = ( k * Convert.ToDecimal(Q1) * Convert.ToDecimal(Q2) / Convert.ToDecimal(r) * Convert.ToDecimal(r));
Console.WriteLine("Answer: " + ans);
Console.ReadLine();
As already pointed out in the comments by Nattrass +5*10^-3 is not a valid input for Convert.ToDecimal().
I assume you want the user to enter the numbers in exponential notation.
So I suggest to change your console input from +5*10^-3 to 5E-3 and use the following snippet to parse your decimal using NumberStyles:
using System.Globalization;
...
// with any you did not have to care about decimal points and thousand sign
// leading sign and so on..
decimal Q1 = Decimal.Parse("5E-3", NumberStyles.Any); // Q1 = 0.005
// or explicit:
decimal Q2 = Decimal.Parse("-1E-1", NumberStyles.AllowExponent
| NumberStyles.AllowDecimalPoint
| NumberStyles.AllowLeadingSign); // Q2 = -0,1
But we have to be careful with the decimal point (dot or comma) so you can just add CultureInfo.InvariantCulture to the parse method.
decimal Q2 = Decimal.Parse( "-1E-1", NumberStyles.AllowExponent
| NumberStyles.AllowDecimalPoint
| NumberStyles.AllowLeadingSign,
CultureInfo.InvariantCulture);
Your code has also some other issues.
For example calculating your constant Decimal k = (9 * 10 ^ 9);
You are using the ^ operator to indicate the power of 9 by a base of ten but in C# it is used as XOR operator. So you should use the Math.Pow() to calculate your constant.
decimal k = (decimal)(9 * Math.Pow(10,9));
You should also avoid Convert.ToString(Console.ReadLine());, because the return value is already a type of string.
You can instead try to cast the input from your console to decimal and avoid the multiple casting in the later code, when calculating. This link may help you to extend your code: How to Read decimal numbers from a user in C#?

How to get the round off value of a decimal in C# [duplicate]

This question already has answers here:
How do you round a number to two decimal places in C#?
(15 answers)
Closed 8 years ago.
I want to get the round off value of a decimal number Suppose I am getting 24.86 than i want to get 25 as final value
Look at Math.Round(decimal) and the overload which accepts a MidpointRounding argument.
Simply
Math.Round(24.86)
This will round you value to 25.
Your own logic will be
decimal d = 1.5m;
decimal r = d - Math.Truncate(d);
if (r > 0)
r = 1 - r;
decimal value = d + r;

How to display number to 2 decimal places in mvc3,C#? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Using String Format to show decimal upto 2 places or simple integer
How to set decimal point in 2 decimal places?
I have Price field in my view. it have the following values 2.5 and 44.
I want to display this value to 2.50 and 44.00 i use the following code
#{decimal prolistprice = decimal.Parse(item.OtherFields["Price"].ToString());}
$#Math.Round(prolistprice, 2, MidpointRounding.AwayFromZero)
in which item.OtherFields["price"] is a object i convert it to string and then decimal
but Math.round is not working it shows 2.5 and 44 only..
Can anyone help this
Math.Round does just that - round.
To format the number you may use .ToString(formatString) like so:
item.OtherFields["price"].ToString("0.00")
Use string format function
1. string.Format("{0:n2}", 200000000.8776);
2. string.Format("{0:n3}", 200000000.8776);
3. string.Format("{0:n2}", 0.3);
/* OUTOUT
1. 200,000,000.88
2. 200,000,000.878
3. 0.30
*/
This should work for you
yourvalue.ToString ("0.00");
decimal dValue = 2.5;
string sDisplayValue = dValue.ToString("0.00");

Categories