decimal price after appliying percent/tax - c#

Helo,
I am making an application for managing budgets in C#, but I have many problems with rounding value. The specification I got was that the user can input the value of the product with and without tax (in two textboxes).
So I'm making a function to convert the price from price with tax to price without tax and price without tax to price with tax.
So I attached it to the TextChanged event of the two textboxes
private void txtPrecioTotal_TextChanged(object sender, EventArgs e)
{
if (!ignoreTextChanged)
{
decimal precio;
if (decimal.TryParse(txtPrecioTotal.Text, out precio))
{
precio = precio / (1 + IVATxt.Value / 100);
ignoreTextChanged = true;
txtPrecioBase.Text = precio.ToString("##.##");
ignoreTextChanged = false;
}
}
}
private void txtPrecioBase_TextChanged(object sender, EventArgs e)
{
if (!ignoreTextChanged)
{
decimal precio;
if (decimal.TryParse(txtPrecioBase.Text, out precio))
{
precio = precio * (1 + IVATxt.Value / 100);
ignoreTextChanged = true;
txtPrecioTotal.Text = precio.ToString("##.##");
ignoreTextChanged = false;
}
}
}
ignoreTextChanged is a bool that prevents recursive calculations
The problem is that the calculations aren't so precise with two digits.
Assuming IVATxt.Value is 21, If for example we enter 100 (price with tax) to the txtPrecioTotal it calculates a value of 82,64 (price without tax) , but if we enter that value in the txtPrecioBase we get 99,99 (price with tax), when it should be 100.
Is there a way to fix this?

Calculate:
82,64 * 1,21 is 99,9944 (which rounds to 99,99)
82,65 * 1,21 is 100,0065 (which rounds to 100,01)
So, there is no way to represent a price with two decimal places that will result to being 100 when 21% tax is applied. How to solve this highly depends on the application scenario (and also possibly legal requirements). What is the user or the application going to do with the value later on?
Some possible ways to deal with this problem. Note that this is highly dependent on the application scenario and also consider legal requirements on how to do calculations for certain taxes in your customers' region.
For calculated values, allow them having more than two decimal places
When the calculated value is only used for informational purposes and not for further calculations, it can be tolerable to use imprecise value.
In a project I was involved, we allowed vouchers to have a marker whether the calculations will be based on net or gross value. When the voucher is marked as being net based, then the user enters net values. When the voucher is marked as being gross based, then the user enters gross values. The tax calculations are then only applied to the sum total of the voucher (resp. the sum totals of items with the same tax class).
...

Finally solved the problem this way:
Changed decimal precision from 2 to 5 digits in the BD
Set to the entity that contains the product, the price when calculated in one of the two textboxes. This price will have a precision of as much as 5. Continuing the example I posted, a price of 100 with the tax I mentioned before was 82.64 without tax, now it will be 82.64463. If I apply to that value the tax of 21%, I now get the value 100,0000023
Then applying the format F2 or C2 I get those prices with two digits. Continuing with the example, the result of the precedent step will be 100,00, which is the price the user entered.
Thank your for all of your answers.

Related

I want to display 13.00 rather than 13

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")

C# Float does not insert as exact value

When inserting a float into a SQL Server database, I'm getting:
5.03000020980835
Which is not the exact value which is being gathered.
How I'm gathering this float? Through a text box control to be converted to float
How I'm working with the data currently:
private void PayRateTextBox_TextChanged(object sender, EventArgs e)
{
PayRateBox = float.Parse(PayRateTextBox.Text);
}
The above is setting an internal float to the current updated textbox which is set:
private float PayRateBox = 0;
Then inserted as:
string Query = "INSERT INTO shifts (ShiftDate,WeekNumber,Hours,PayType,Rate) " +
"VALUES(#Date, #WeekNo, #Hours, #PayType, #Rate)";
and bound to the query via bound parameters:
CMD.Parameters.Add("#Rate", SqlDbType.Float);
CMD.Parameters["#Rate"].Value = PayRate;
The default text in the TextBox is set to 5.03, so somewhere along the lines other data is being appended to make the overall value increment. I have tried to trace where this is happening, but cannot find out how and why this is happening. Perhaps I'm overlooking something?
Precision of float is limited to 7 significant digits. In your case it means 5.030000. Values at the rest of decimal places are undefined.
To improve precision use either double with precision of 15-16 significant digits or decimal with 28-29 significant digits.

Truncating in C#

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

to compare double and decimal should I cast double to decimal or decimal to double?

I need to compare two values.
One value is price which represents current price of something and so decimal because you actually can buy or sell something by this price.
Another value is estimatedPrice which is the result of mathematical calculations and so double because it's just estimation and you can not actually do any "operations" by this esitmatedPrice
now i want to buy if price < estimatedPrice.
So should i cast price to double or estimatedPrice to decimal?
I understand that after casting I will get "slighty another" numbers, but it seems I don't have other options.
It depends on the data. Decimal has greater precision; double has greater range. If the double could be outside the decimal range, you should cast the decimal to double (or indeed you could write a method that returns a result without casting, if the double value is outside the decimal range; see example below).
In this case, it seems unlikely that the double value would be outside the decimal range, so (especially since you're working with price data) you should cast the double to decimal.
Example (could use some logic to handle NaN values):
private static int Compare(double d, decimal m)
{
const double decimalMin = (double)decimal.MinValue;
const double decimalMax = (double)decimal.MaxValue;
if (d < decimalMin) return -1;
if (d > decimalMax) return 1;
return ((decimal)d).CompareTo(m);
}
decimal vs double! - Which one should I use and when?
If you're more concerned with precision, convert to decimal. If you're not, go with doubles.
I've never worked with prices before in software, but from what I've heard, many deal with integers. For example, for $1.23, store it as the integer 123. The conversion to a decimal is done at the very end when you output results to the user.
Similarly, for your estimated price, can you deal with numbers that are (say) 100 times larger?
I recommend you to convert to decimal. because it seems you want manipulate money values. but I can give this short answer : for accurate (manipulating money value specially for financial applications) application use decimal. and if you prefer less resource and more speed use double.

How to round a decimal amount, in c sharp, to a nearest fractional value given by users?

Requirement
User has option to choose fractional value as a rule. For example 0.5, or 0.01, or 0.33, or 0.1.
Amount is for example 12.46 and rounding rule is 0.01.
I am not sure if i have explained it correctly.
Any answer is highly appreciated. Khankooouuu in advance.
public class Test
{
static double round(double what, double to)
{
return to * Math.Round(what/to);
}
public static void Main()
{
Console.WriteLine(round(3.5, 1));
Console.WriteLine(round(3.44, 1));
Console.WriteLine(round(3.44, 0.1));
Console.WriteLine(round(1.68, 0.33));
Console.WriteLine(round(1.59, 0.33));
}
}
outputs
4
3
3.4
1.65
1.65
You can round a decimal by using the Decimal.Round() method with an overload of Decimal and an integer for how many decimal places. See Here.
As for the part to see how many decimal places the user wants to use if they put in a decimal value, you can convert that to a string and count the characters after the decimal point:
decimal UserDecimal;
string UserString = UserDecimal.ToString();
int DecimalPlaces = UserString.SubString(UserString.IndexOf(".")).Length;
At the end of all that, DecimalPlaces will be the amount of decimal places the user has implicitly requested with their inputed decimal value.
This what you're looking for??

Categories