Formatting a double to two decimal places - c#

I have been trying to make the answer this prints out to be to two decimal places. All the math involved has to stay at that format of two decimal places. I have tried a few things and I am not sure what to change to make this work.
double pdt1 = 239.99;
double pdt1Total;
double pdt2 = 129.75;
double pdt2Total;
double pdt3 = 99.95;
double pdt3Total;
double pdt4 = 350.89;
double pdt4Total;
double wage = 200;
double percentage = 9;
double total;
double answer;
double i = 100;
double a;
double b;
double c;
double d;
Console.Write("Enter number sold of product #1: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #2: ");
b = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #3: ");
c = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #4: ");
d = Convert.ToInt32(Console.ReadLine());
pdt1Total = a * pdt1;
pdt2Total = b * pdt2;
pdt3Total = c * pdt3;
pdt4Total = d * pdt4;
total = (pdt1Total + pdt2Total + pdt3Total + pdt4Total);
string.Format("{0:0.00}", total);
string.Format("{0:0.00}", answer = (total * percentage / i) + wage);
Console.WriteLine("Earnings this week: "+answer+"");

string.Format will not change the original value, but it will return a formatted string. For example:
Console.WriteLine("Earnings this week: {0:0.00}", answer);
Note: Console.WriteLine allows inline string formatting. The above is equivalent to:
Console.WriteLine("Earnings this week: " + string.Format("{0:0.00}", answer));

Well, depending on your needs you can choose any of the following. Out put is written against each method
You can choose the one you need
This will round
decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58
This will ensure that 2 decimal places are written.
d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50
if you want to write commas you can use this
d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54
if you want to return the rounded of decimal value you can do this
d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58

You can round a double to two decimal places like this:
double c;
c = Math.Round(c, 2);
But beware rounding will eventually bite you, so use it with caution.
Instead use the decimal data type.

I would recomment the Fixed-Point ("F") format specifier (as mentioned by Ehsan). See the Standard Numeric Format Strings.
With this option you can even have a configurable number of decimal places:
public string ValueAsString(double value, int decimalPlaces)
{
return value.ToString($"F{decimalPlaces}");
}

double d = 3.1493745;
string s = $"{d:0.00}"; // or $"{d:#.##}"
Console.WriteLine(s); // Displays 3.15

Since you are working in currency why not simply do this:
Console.Writeline("Earnings this week: {0:c}", answer);
This will format answer as currency, so on my machine (UK) it will come out as:
Earnings this week: £209.00

The problem is that when you are doing additions and multiplications of numbers all with two decimal places, you expect there will be no rounding errors, but remember the internal representation of double is in base 2, not in base 10 ! So a number like 0.1 in base 10 may be in base 2 : 0.101010101010110011... with an infinite number of decimals (the value stored in the double will be a number N with :
0.1-Math.Pow(2,-64) < N < 0.1+Math.Pow(2,-64)
As a consequence an operation like 12.3 + 0.1 may be not the same exact 64 bits double value as 12.4 (or 12.456 * 10 may be not the same as 124.56) because of rounding errors.
For example if you store in a Database the result of 12.3 +0.1 into a table/column field of type double precision number and then SELECT WHERE xx=12.4 you may realize that you stored a number that is not exactly 12.4 and the Sql select will not return the record;
So if you cannot use the decimal datatype (which has internal representation in base 10) and must use the 'double' datatype, you have to do some normalization after each addition or multiplication :
double freqMHz= freqkHz.MulRound(0.001); // freqkHz*0.001
double amountEuro= amountEuro.AddRound(delta); // amountEuro+delta
public static double AddRound(this double d,double val)
{
return double.Parse(string.Format("{0:g14}", d+val));
}
public static double MulRound(this double d,double val)
{
return double.Parse(string.Format("{0:g14}", d*val));
}

If you want 0.5 instead of .5, use d.ToString("0.##").

Related

converting int to decimal choosing where to put decimal place

I have an interesting problem, I need to convert an int to a decimal.
So for example given:
int number = 2423;
decimal convertedNumber = Int2Dec(number,2);
// decimal should equal 24.23
decimal convertedNumber2 = Int2Dec(number,3);
// decimal should equal 2.423
I have played around, and this function works, I just hate that I have to create a string and convert it to a decimal, it doesn't seem very efficient:
decimal IntToDecConverter(int number, int precision)
{
decimal percisionNumber = Convert.ToDecimal("1".PadRight(precision+1,'0'));
return Convert.ToDecimal(number / percisionNumber);
}
Since you are trying to make the number smaller couldn't you just divide by 10 (1 decimal place), 100 (2 decimal places), 1000 (3 decimal places), etc.
Notice the pattern yet? As we increase the digits to the right of the decimal place we also increase the initial value being divided (10 for 1 digit after the decimal place, 100 for 2 digits after the decimal place, etc.) by ten times that.
So the pattern signifies we are dealing with a power of 10 (Math.Pow(10, x)).
Given an input (number of decimal places) make the conversion based on that.
Example:
int x = 1956;
int powBy=3;
decimal d = x/(decimal)Math.Pow(10.00, powBy);
//from 1956 to 1.956 based on powBy
With that being said, wrap it into a function:
decimal IntToDec(int x, int powBy)
{
return x/(decimal)Math.Pow(10.00, powBy);
}
Call it like so:
decimal d = IntToDec(1956, 3);
Going the opposite direction
You could also do the opposite if someone stated they wanted to take a decimal like 19.56 and convert it to an int. You'd still use the Pow mechanism but instead of dividing you would multiply.
double d=19.56;
int powBy=2;
double n = d*Math.Pow(10, powBy);
You can try create decimal explictly with the constructor which has been specially designed for this:
public static decimal IntToDecConverter(int number, int precision) {
return new decimal(Math.Abs(number), 0, 0, number < 0, (byte)precision);
}
E.g.
Console.WriteLine(IntToDecConverter(2423, 2));
Console.WriteLine(IntToDecConverter(1956, 3));
Outcome:
24.23
1.956
Moving the decimal point like that is just a function of multiplying/dividing by a power of 10.
So this function would work:
decimal IntToDecConverter(int number, int precision)
{
// -1 flips the number so its a fraction; same as dividing below
decimal factor = (decimal)Math.Pow(10, -1*precision)
return number * factor;
}
number/percisionNumber will give you an integer which you then convert to decimal.
Try...
return Convert.ToDecimal(number) / percisionNumber;
Convert your method like as below
public static decimal IntToDecConverter(int number, int precision)
{
return = number / ((decimal)(Math.Pow(10, precision)));
}
Check the live fiddle here.

How do i hold the correct output value without roundoff the double value in given program

Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal's total cost.
Condition: Be sure to use precise values for your calculations, or you may end up with an incorrectly rounded result!
Here is my Program:
static void Main(String[] args)
{
double mealCost=Convert.ToDouble(Console.ReadLine());
int tipPercent=Convert.ToInt32(Console.ReadLine());
int taxPercent=Convert.ToInt32(Console.ReadLine());
double tip,tax;
tip=(mealCost*(tipPercent/100));
tax=(mealCost*(taxPercent/100));
double totalCost=mealCost+tip+tax;
Console.WriteLine("The total meal cost is {0} dollars",totalCost);
Console.ReadLine();
}
But I had the output as 12.
My Expected output is 15.
If my sample input is 12.00 20 8
My calculation as tip=2.4 and tax=0.96, totalCost=15.36
and the rounded value is
(round)totalCost=15.
But the output came as 12.
How do I get the correct output in C#. Can anyone provide me some suggestions to resolve this issue.
What you have to do is, take tipPercent and taxPercent as double values or else implicitly convert them to double before processing division like the following:
tip = (mealCost * ((double)tipPercent / 100));
tax = (mealCost * ((double)taxPercent / 100));
Then you will get totalCost=15.36 for the input specified in the question. Much smarter solution is :
double mealCost, tipPercent, taxPercent;
Console.WriteLine("Enter values for Meal Cost, Tip percentage and tax percentage");
if (!double.TryParse(Console.ReadLine(), out mealCost))
{
Console.WriteLine("Invalid input for meal Cost");
}
if (!double.TryParse(Console.ReadLine(), out tipPercent))
{
Console.WriteLine("Invalid input for Tip percentage");
}
if (!double.TryParse(Console.ReadLine(), out taxPercent))
{
Console.WriteLine("Invalid input for Tip tax Percent");
}
double tip = (mealCost * (tipPercent / 100));
double tax = (mealCost * (taxPercent / 100));
double totalCost = mealCost + tip + tax;
Console.WriteLine("The total meal cost is {0}", totalCost.ToString("C0"));
Console.ReadLine();
First, please change your data type to decimal instead of double, more suitable for money related.
Second, when you do the calculation, C# will try to return with the same data type, which caused:
tip=(mealCost*(tipPercent/100)); // it will turn tipPercent/100 to int, which is 0
tax=(mealCost*(taxPercent/100)); // same here
You have many way to do it, like cast as double:
tip = (mealCost * ((double) tipPercent / 100));
State the 100 to 100D (tell c# it is double)
tip = (meanCost * (tipPercent / 100D));
Or, just use double / decimal for your tipPercent and taxPercent
double tipPercent = Convert.ToDouble(Console.ReadLine());
in division you should have at least one double to get answer in double very less change you need to make it work see bellow
static void Main(String[] args)
{
double mealCost=Convert.ToDouble(Console.ReadLine());
int tipPercent=Convert.ToInt32(Console.ReadLine());
int taxPercent=Convert.ToInt32(Console.ReadLine());
double tip,tax;
tip=(mealCost*(tipPercent/100.0));//change 100 to 100.0
tax=(mealCost*(taxPercent/100.0));//change 100 to 100.0
double totalCost=mealCost+tip+tax;
Console.WriteLine("The total meal cost is {0} dollars",totalCost);
Console.ReadLine();
}
Your problem is related to this two lines:
tip=(mealCost*(tipPercent/100));
tax=(mealCost*(taxPercent/100));
These define operations between integer and will return integers. Cast to double or declare 100 as double like this: 100d
You are getting 0 since you code divide an int value by an int value. The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. You can review how C# handles it here.
If you rewrite your tip, tax calculation with following.
tip = (mealCost * tipPercent / 100);
tax = (mealCost * taxPercent / 100);

calculating a percentage from a value C#

I'm trying to output a percentage from a value imputed from a textbox. Here is my code;
int firstNumber;
double mydouble1 = 0.15;
int myint1 = (int)mydouble1;
int.TryParse(HouseValue.Text, out firstNumber);
int answer;
answer = (firstNumber) * (myint1);
prem1.Text = answer.ToString();
The problem is when I run the app and enter a value to calculate, the answer is 0. I cant seem to get it to display the correct amount for 0.15% of the value.
Try this: change your answer from an int to a double:
int firstNumber;
double mydouble1 = 0.15;
if (int.TryParse(HouseValue.Text, out firstNumber))
{
double answer = firstNumber * mydouble1;
prem1.Text = answer.ToString(); // you may want to round/format this
}
The problem is that casting 0.15 to int makes it 0
(int)0.15 == 0
The double type has primarily been made for scientific calculations. You should use decimal when dealing with money, since decimal fractions can often not be translated into binary numbers (used internally to store doubles) without loss of precision.
decimal percentage = 0.15m;
int houseValue;
if (Int32.TryParse(HouseValue.Text, out houseValue)) {
decimal result = Math.Round(percentage * houseValue);
prem1.Text = result.ToString();
} else {
prem1.Text = "Please enter valid house value!";
}
firstNumber, myint1 and mydouble1 are terrible names. Use speaking names!
Except error handling in converting string to int, use following code:
double mydouble1 = 0.15;
double percentage = int.Parse(ouseValue.Text) * mydouble1;

Show decimal value upto nth places in c#

I know we can display decimals up to certain no of places (if that no of places is fixed). For example, we can display up to 2 places using String.Format:
String.Format("{0:0.00}", 123.4567);
But our requirement is, we have to fetch no of decimal places from database and display the decimal value up to that place. For example:
int n=no of decimal places
I want to write something like:
String.Format("{0:0.n}", 123.4567);
Any suggestions would be of great help.
Added Note: String.Format rounds off the digit. I am looking for something to omit the remaining digits.
Perhaps:
int n = 3;
string format = String.Format("{{0:0.{0}}}", new string('0', n));
Console.Write(String.Format(format, 123.4567)); // 123,457
as method:
public static string FormatNumber(double d, int decimalPlaces)
{
string format = String.Format("{{0:0.{0}}}", new string('0', decimalPlaces));
return String.Format(format, d);
}
or even simpler, using ToString + N format specifier:
public static string FormatNumber(double d, int decimalPlaces)
{
return d.ToString("N" + decimalPlaces);
}
if you don't want the default rounding behaviour but you just want to truncate the remaining decimal places:
public static string FormatNumberNoRounding(double d, int decimalPlaces)
{
double factor = Math.Pow(10, decimalPlaces);
double truncated = Math.Floor(d * factor) / factor;
return truncated.ToString();
}
If you prefer less string formatting, this is perhaps simpler:
decimal d = 123.4567
Console.Write("rounded: {0}", decimial.Round(d, 3));
Additionally, you can control the type of rounding used:
decimial.Round(d, 3, MidpointRounding.AwayFromZero)
Since not many people realise that .NET's default rounding method is ToEven, which rounds to the nearest even number. So values like 2.5 actually round to 2, not 3.

C# - Truncating after a position

I have a double typed variable. This variable stores information that is part of a more complex formula. Importantly, this variable can only include information up to the tenths location, or one decimal position (i.e. 10.1, 100.2, etc). However, when determining this value, it must be calculated such that anything past the tenths location is truncated, not rounded. For instance:
if the value equals 10.44, The variable value should be 10.4.
if the value equals 10.45, The variable value should also be set to 10.4
How do I truncate values in C# with respect to a decimal place?
Using an extension method:
public static double RoundDown(this double value, int digits)
{
int factor = Math.Pow(10,digits);
return Math.Truncate(value * factor) / factor;
}
Then you simply use it like this:
double rounded = number.RoundDown(2);
You have to do that by your own:
public static decimal Truncate(decimal value, int decimals)
{
if ((decimals < 0) || (decimals > 28))
{
throw new ArgumentOutOfRangeException("decimals", "The number of fractional decimals must be between 0 and 28.");
}
decimal integral = Math.Truncate(value);
decimal fractional = value - integral;
decimal shift = (decimal)Math.Pow(10, decimals);
fractional = Math.Truncate(shift * fractional);
fractional = fractional / shift;
return (integral + fractional);
}
System.Math.Truncate (d * 10) / 10
Generally, if you're working with numbers where the precise decimal representation is important, you should use decimal - not double.
With decimal, you can do something like...
decimal d = ...;
d = decimal.Truncate(d*10)/10;
If you use a double value, your truncated number will not generally be precisely representable - you may end up with excess digits or minor rounding errors. For example Math.Truncate((4.1-4.0)*10) is not 1, but 0.
While I would probably use Phillippe's answer, if you wanted to avoid scaling the number up (unlikely to be a problem for 1dp), you could:
public static double RoundDown(this double x, int numPlaces)
{
double output = Math.Round(x, numPlaces, MidpointRounding.AwayFromZero);
return (output > x ? output - Math.Pow(10, -numPlaces) : output);
}

Categories

Resources