Converting string/int to double in C# - c#

Here is a simple calculator, to calculate how much candy you can get when dividing the kilogram price with the money you have allocated for candy.
In example: "Candy costs 5$ a kilo. I have 3.50$ allocated for candy. I would use this program to calculate the amount of candy I get."
It works fine until using decimals. I want to convert the string to Double so I can use decimals with the calculator. 4$ kilo price and 8$ money of course results to 2 kilos of candy. But if the kilo price was 4.80$ and I had 9.30$ money, I would only get an error and cause the command prompt to crash.
static void Main(string[] args)
{
//The variables
int int1;
int int2;
string text1;
string text2;
//The actual calculation
System.Console.Write("Please input the kilogram price of candy: ");
text1 = System.Console.ReadLine();
int1 = int.Parse(text1);
System.Console.Write("Please input the money allocated for candy ");
text2 = System.Console.ReadLine();
int2 = int.Parse(text2);
System.Console.WriteLine("With the amount of money you input you would get " + (int2 / int1) + " kilos of candy.");
}
}
}

You're using int variable types, which can only contain integer numbers, i.e. "whole" numbers without decimals, such as 1 and 42. As soon as you want to use decimals, you'll need a variable type that can support this.
C# has a few of those built in: float, double and decimal. Given you're working with monetary data, where precision and accuracy are very important, you must use decimal.
You also want to use the bool-returning TryParse() as opposed to the exception-throwing Parse() method.
So change your code to use decimal and decimal.TryParse():
decimal pricePerKilogram;
string input = Console.ReadLine();
if (!decimal.TryParse(input, out pricePerKilogram))
{
// show error or retry
}

You need to parse your inputs from decimal, not int. Here, try it this way:
System.Console.Write("Please input the kilogram price of candy: ");
decimal pricePerKilo = decimal.Parse(System.Console.ReadLine());
System.Console.Write("Please input the money allocated for candy ");
decimal amountAllocatedForCandy = decimal.Parse(System.Console.ReadLine());
System.Console.WriteLine("With the amount of money you input you would get " + (amountAllocatedForCandy / pricePerKilo) + " kilos of candy.");
System.Console.Read();
An int is a type that can only store whole numbers -- i.e. no fractional component/decimal digits -- which is why you got an error when you tried to parse a string number with decimal digits into an int. A decimal, on the other hand, is used to store numbers with fractional components.
Each type has its uses: you would never want to store, say, number of candy pieces using a decimal since that can only be a whole number. Doing so could lead to unnecessary confusion for future maintainers of your code and could lead to bugs that are hard to find.

that is because 4.80 or 9.30 is not integer.
double double1;
double double2;
string text1;
string text2;
//The actual calculation
System.Console.Write("Please input the kilogram price of candy: ");
text1 = System.Console.ReadLine();
double1 = double.Parse(text1);
System.Console.Write("Please input the money allocated for candy ");
text2 = System.Console.ReadLine();
double2 = double.Parse(text2);
System.Console.WriteLine("With the amount of money you input you would get " + (double2 / double1) + " kilos of candy.");
NOTE: INT stores integer value like 1 2 3 4 etc...

As to your question:
Just use doubles decimals in the first place!
decimal price;
decimal allowance;
Also, some additional unsolicited advice:
You've got a few issues here.
First of all, you'll need to swap your division in the WriteLine statement to get the correct calculation.
Also, I'd recommend renaming your variables to something more descriptive.
Here's your code with some modifications. I've commented each change.
//The variables
decimal price; //CHANGE: descriptive variables!
decimal allowance;
string priceInput;
string allowanceInput;
//The actual calculation
System.Console.Write("Please input the kilogram price of candy: ");
priceInput = System.Console.ReadLine();
price = decimal.Parse(priceInput); //CHANGE: use double.Parse here instead of int.Parse
System.Console.Write("Please input the money allocated for candy ");
allowanceInput = System.Console.ReadLine();
allowance = decimal.Parse(allowanceInput); //CHANGE: use double.Parse here instead of int.Parse
System.Console.WriteLine("With the amount of money you input you would get "
+ Math.Round(allowance / price, 2) + " kilos of candy.");
//CHANGE: Divide the money you have by the amount it costs to get the KG of candy.
EDIT: Added decimals due to working with money.

Related

Format string % without multiply the value by 100

I need to format the string as % but the user will enter the number already as %
i.e user enter 10, I need to show 10%
I tried {0:P} and {0:0%} but it always multiply the user number by 100
How can I simply add "%" to the input number without multiply it by 100 in the format {0:}?
You have two real options, add the % by hand
String.Format("Example: {0}%", userValue);
or devide the user number by 100 before you display it.
String.Format("Example: {0:P}", userValue / 100.0); //don't just do "100" or you will get errors from integer division if userValue is a int.
Can't you just append %:
userEnteredNumber.ToString() + "%";
What about
var showString = userInput + "%";
Then display showString wherever you need to show.
We use this format for formatting int value to percent without multipying by 100.
intPercent.ToString(#"0\%");

How to format output to two decimal places and '$' symbol in C#?

Newbie to the C# language and
I just finished creating a loan mortgage calculator and I am having trouble formatting my code below. What I am trying to do is format the monthly payment value to 2 decimal places and add the '$' symbol. Any help would be appreciated. Thanks!
Example input for my principle amount:
//User input for Principle amount in dollars
Console.Write("Enter the loan amount, in dollars(0000.00): ");
principleInput = Console.ReadLine();
principle = double.Parse(principleInput);
//Prompt the user to reenter any illegal input
if (principle < 0)
{
Console.WriteLine("The value for the mortgage cannot be a negative value");
principle = 0;
}
//Calculate the monthly payment
double loanM = (interest / 1200.0);
double numberMonths = years * 12;
double negNumberMonths = 0 - numberMonths;
double monthlyPayment = principle * loanM / (1 - System.Math.Pow((1 + loanM), negNumberMonths));
//Output the result of the monthly payment
Console.WriteLine("The amount of the monthly payment is: " + monthlyPayment);
Console.WriteLine();
Console.WriteLine("Press the Enter key to end. . .");
Console.Read();
What I am trying to do is format the monthly payment value to 2 decimal places and add the '$' symbol.
It sounds like you want to use the currency format specifier.
Console.WriteLine("The amount of the monthly payment is: {0:c}", monthlyPayment);
That won't always use the dollar symbol of course - it will use the currency symbol for the thread's current culture. You can always specify CultureInfo.InvariantCulture explicitly.
However, I'd strongly advise you not to use double for currency values. Use decimal instead.
From MSDN: Standard Numeric Format Strings
(look for 'The Currency ("C") Format Specifier')
Console.WriteLine("The amount of the monthly payment is: {0:C2} ", monthlyPayment);
You can use the Math.Round() function:
double inputNumber = 90.0001;
string outputNumber = "$" + Math.Round(inputNumber, 2).ToString();
To use 2 decimal places you can use:
Console.WriteLine("The amount of the monthly payment is: "$ " + Math.Round(monthlyPayment,2));

Math.Floor Behaviour

double c, d, e;
double a = (c - d) / e;
double b = Math.Floor(a);
Debug.WriteLine(a.ToString() + " " + b.ToString());
Code above outputs "3 2" at one configuration where all numbers are double. How is this possible? Is it because of fractional error resulting from double operations? However I think a.ToString() should give the whole number with its fractional part.
It's just a matter of what double.ToString() does. Here's a short but complete program demonstrating the same thing:
using System;
public class Test
{
static void Main(string[] args)
{
// Find the largest double less than 3
long bits = BitConverter.DoubleToInt64Bits(3);
double a = BitConverter.Int64BitsToDouble(bits - 1);
double b = Math.Floor(a);
// Print them using the default conversion to string...
Console.WriteLine(a.ToString() + " " + b.ToString());
// Now use round-trip formatting...
Console.WriteLine(a.ToString("r") + " " + b.ToString("r"));
}
}
Output:
3 2
2.9999999999999996 2
Now double.ToString() is documented with:
This version of the ToString method implicitly uses the general numeric format specifier ("G") and the NumberFormatInfo for the current culture.
... and the general numeric format specifier docs state:
The precision specifier defines the maximum number of significant digits that can appear in the result string. If the precision specifier is omitted or zero, the type of the number determines the default precision, as indicated in the following table.
... where the table shows that the default precision for double is 15. If you consider 2.9999999999999996 rounded to 15 significant digits, you end up with 3.
In fact, the exact value of a here is:
2.999999999999999555910790149937383830547332763671875
... which again, is 3 when regarded with 15 significant digits.

I want to print the value in sales

I want to print the value of the amount of sales entered by user times .10. My first issue is I want to store a value that a user enters into sales then times that by .10 then print the value of sales. We I run the program I get two lines one is the amount of sales entered the other is .5.
const double COMMRATE = 0.10;
string inputstring;
double sales =5;
char response;
Console.Write("Do you want to Calculate Sales A or B or E...");
inputstring = Console.ReadLine();
response = Convert.ToChar(inputstring);
while (response == 'A')
{
Console.WriteLine("Enter Sales", sales.ToString("C"));
sales = sales * COMMRATE;
inputstring = Console.ReadLine();
response = Convert.ToChar(inputstring);
}
Your .5 is coming about because you've set the default value of sales to be 5, and 5 * 0.1 = 0.5.
But why is that happening? Let's take apart your loop:
It asks the user to enter an amount of sales. The second parameter is ignored, because "Enter Sales" has no format string placeholders. It does not perform line-reading of any form.
Without asking for input, it multiplies Sales by the commission rate and stores that to Sales.
Now it asks for user input,
which it immediately spits back out exactly as written (the amount-of-sales-entered line.)
What you actually need to be doing is a second Console.ReadLine() to get a string for the amount of sales, then use Double.ParseDouble() to get the entered amount of sales. Multiply that by your COMMRATE and print that back out- then give your "Do you want to Calculate..." question again, and then use the response from that to decide whether or not to continue the loop- currently, response is never getting modified, so you've created an infinite loop.
Unfortunately, you aren't even really close to the right code here. Your loop should look more like
while (response == 'A'){
Console.WriteLine("Enter Sales");
string salesStr = Console.ReadLine();
Console.WriteLine(Double.Parse(salesStr) * COMMRATE);
Console.WriteLine("Enter A to continue, anything else to quit");
response = Convert.ToChar(Console.ReadLine());
}
...which should get you started towards making your program do what you want.
Is this what you intend?
const double COMMRATE = 0.10;
string inputstring;
double sales;
char response;
Console.Write("Do you want to Calculate Sales A or B or E...");
inputstring = Console.ReadLine();
response = Convert.ToChar(inputstring);
while (response == 'A')
{
Console.WriteLine("Enter Sales");
inputstring = Console.ReadLine();
sales = Double.Parse(inputstring);
Console.WriteLine("Sales = " & sales);
Console.WriteLine("Commission = " & sales * COMMRATE);
}
I'm having a hard time discerning what exactly you're asking.
If you want to print the value multiplied by the COMMRATE then you should probably put the calculation above the write statement.
sales = sales * COMMRATE;
Console.WriteLine("Enter Sales", sales.ToString("C"));
Although since you said you want to STORE the value entered by the user and THEN print it times the COMMRATE maybe you should use something like
double calculatedSales = sales * COMMRATE
Console.WriteLine("Enter Sales", calculatedSales.ToString("C"));
so that you're not redefining the original sales amount

Remove 0s from the end of a decimal value [duplicate]

This question already has answers here:
Remove trailing zeros
(23 answers)
Closed 9 years ago.
I have a decimal value that has a variable number of digits after the ., for example:
0.0030
0.0310
0.0001
1.1200
How can I write a dynamic function that removes 0 in the end of the decimal?
You can also modify the decimal itself so that any ToString() will give you what you want
(more details in my answer here) :
public static decimal Normalize(decimal value)
{
return value/1.000000000000000000000000000000000m;
}
string.Format("{0:0.#####}", 0.0030)
or
var money=1.3000m;
money.ToString("0.#####");
For future reference I recommend the .NET Format String Quick Reference by John Sheehan.
decimal value = 0.0030m;
value.ToString(“G29″);
Edit: The G formatter does work, the only problem is that it jumps to scientific notation if there are too many significant figures in the original decimal. Not so ideal.
See the "The General ("G") Format Specifier" documentation here: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#GFormatString
I'm on lunch, so I did a little test:
decimal d1 = 0.000100m;
decimal d2 = 0.001000000000000000000000m;
decimal d3 = 0.000000000000001000000000m;
Console.WriteLine(Environment.NewLine + "input decimal: 0.000100m");
Console.WriteLine("G " + d1.ToString("G"));
Console.WriteLine("G29 " + d1.ToString("G29"));
Console.WriteLine("0.####### " + d1.ToString("0.#######"));
Console.WriteLine(Environment.NewLine + "input decimal: 0.001000000000000000000000m");
Console.WriteLine("G " + d2.ToString("G"));
Console.WriteLine("G29 " + d2.ToString("G29"));
Console.WriteLine("0.####### " + d2.ToString("0.#######"));
Console.WriteLine(Environment.NewLine + "input decimal: 0.000000000000001000000000m");
Console.WriteLine("G " + d3.ToString("G"));
Console.WriteLine("G29 " + d3.ToString("G29"));
Console.WriteLine("0.####### " + d3.ToString("0.#######"));
Output:
input decimal: 0.000100m
G 0.000100
G29 0.0001
0.####### 0.0001
input decimal: 0.001000000000000000000000m
G 0.001000000000000000000000
G29 0.001
0.####### 0.001
input decimal: 0.000000000000001000000000m
G 0.000000000000001000000000
G29 1E-15
0.####### 0
Hmm, this is a display formatting issue (the zeros are added when you convert the decimal to a string).
You need to see where in code you are seeing the trailing zeros. Is it after a call to .ToString()? Try playing around with the different formatting strings:
.ToString("#");
.ToString("0.00");
.ToString("#.##");
And so on. The best way to do this is just to experiment with the different possible values.
decimal m = 0.030000m;
Console.Write(m.ToString("0.##########"));
Just make sure you have enough #s for the number of decimal places you want to display
I use the following. It ensures that any decimal (for which the max precision is 29 decimal places) will show all available digits of precision without trailing zeros, and without your code needing to have a long ugly string of hash marks.
if (value is Decimal)
value = ((Decimal)value).ToString("0.".PadRight(29, '#'), culture);
public static string GentlyRemoveEndZeros(string input)
{
// if (input == null) return null;
// if (input == "") return "";
if (input.Contains(".")) return input.TrimEnd('0').TrimEnd('.');
return input;
}

Categories

Resources