c# large fractional decimal split - c#

My Requirement is Fractional Amount FIrst 2 decimal part add customer bank account and others fractional part add in dispute wallet account .
var amount = 40.235667745465465
I want to convert it 2 different variable
var customerBalance = // ??? - should be 40.23
var disputeBalance = amount - customerBalance
How can I do calculate the step marked ??? ?

This will work fine.
var firstAmount = Math.Floor(amount / 0.01) / 100 ;
var secondVariable = amount - firstAmount;

You probably want:
var firstAmount = Math.Round(amount, 2);
but note that this can round up as well as down; you may want to check whether secondVariable comes out negative, and if so: compensate.
Another way to look at it is to multiply by 100 and take the integer/decimal parts (hint: Math.Floor), then divide by 100 again.

If you are looking for a string, then it can be:
string secondVariableAsString = string.Format("{0:0.00}", secondVariable);
Another is:
Math.Truncate(100 * secondVariable) / 100;
However, this will cause overflow for large numbers.

Related

Decimal rounding issues

I have a scenario in which some variable values have decimal values, the values can have leading .0, .234, .124, .125, numbers like this, and so on. If the number has leading decimal and zero it should ignore and if a number has leading 3 or more numbers it should round off to two.
Let's say the code is as follows:
var anone = "23"
var antwo = "23.0"
var anthree = "23.467"
var anfour = "23.125"
In order to remove the leading decimal and zero I have used the following method:
var removingzero = antwo.Replace(".0", "");
// The result will be = 23
In order to round off and limit the number to two decimal points I have used the following method:
var convertodecimal = Decimal.Parse(anthree);
var roundtotwo = Math.Round(convertodecimal, 2);
// The result will be = 23.47
similarly in order to convert the last one I follow the same method:
var convertodecimal = Decimal.Parse(anfour);
var roundtotwo = Math.Round(convertodecimal, 2);
// The result will be = 23.12
// But the Result should be = 23.13
So, the problem is when I am trying to round off any number like the last example it does not do it, how can I fix it.
It sounds like your question is a long way of asking "How can I force rounding UP when a decimal number ends in 5?"
If that's the case, then you can use the overload of Math.Round that takes a MidpointRounding argument, and specify either MidpointRounding.AwayFromZero or MidpointRounding.ToPositiveInfinity.
The behavior of these is the same for positive numbers, but difference is seen with negative numbers, where -23.125 will round to -23.13 if AwayFromZero is specified, or -23.12 if ToPositiveInfinity is specified.
So your code might look like this instead:
var roundtotwo = Math.Round(convertodecimal, 2, MidpointRounding.AwayFromZero);
Try by changing your Math.Round() to below one:
Math.Round(num,2, MidpointRounding.AwayFromZero)

Dividing prices by 3

For accounting program I need to divide a price by 3 so it can be shared over 3 months
For example 9€
3€ first month
3€ second month
3€ third month
Now this would be price/3
But what if the number is 10?
3,33€ first month
3,33€ second month
3,33€ last month
3,33€*3 =€9.99
One cent has gone missing.
How can I make it so the ouput would become 3,33€ , 3,33€ , 3,34€?
You need to ask the accountant what they would want here. That's an important thing to do in software development: ask the users.
Normally, for stability, you would subtract the amounts paid from a balance account, and put checks in to ensure that the balance falls to zero.
And don't ever use a floating point data type when building accounting software. Floating point precision will bite you. Use a currency type instead.
You could set the last by making up the difference, instead of via the same calculation as the rest. In pseudocode:
normalMonthPrice = RoundToTwoPlaces(totalPrice / months);
lastMonthPrice = totalPrice - (normalMonthPrice * (months - 1));
As Bathsheba said, ask your users first.
Here's a technique that I've used often in such scenarios. This method will ensure the most even distribution, with the upward bias toward the end. For example, if you call DivvyUp(101, 3), you'll get 33.66, 33.67, 33.67. Notice that the difference isn't just made up for at the end. Instead, each value is computed according to what's left, not what was started with.
public static double[] DivvyUp(double total, uint count)
{
var parts = new double[count];
for (var i = 0; i < count; ++i)
{
var part = Math.Truncate((100d * total) / (count - i)) / 100d;
parts[i] = part;
total -= part;
}
return parts;
}
Congratulations, you've found out why the computing world isn't as simple as "put math on it"-
The easiest solution would be to divide by 3, round to two decimal places, and use that value for the first two months, and original - 2 * perMonth for the rest.

Using the mod operator to decrease value in a textbox

Okay so I have created this vending machine application form and I am having problems getting rid of the change. The machine has 50 10p's in at the start of the day. A fizzy drink costs 40p, so, if the user puts in 50p, he will get change back of 10p. I have a textbox showing the amount of 10p's in the machine, so at the start, 50, after he puts in 50p it will be 55. However, now that he has to get 10p change (I have a release change button), I want the amount of 10p's in the textbox to go to 54...any ideas? I tried using the mod operator but wasn't sure how to use it:
decimal change = decimal.Parse(txtChange.Text)
if (change % 10 > 1)
{
int tenPenny = int.Parse(txt_BoxTenPenny.Text);
int totalTenPen = tenPenny - 1;
txt_BoxTenPenny.Text = totalTenPen.ToString();
}
I know this isn't right, when I was doing research, they were using the % operator and using the number 10 as the numerator..so..I got a bit lost. Any suggestions would be great!
If you're trying to determine how many 10 pennies the user is owed, this is calculated using:
int tenPennies = change / 10
As opposed to the modulus (%) operator, so:
decimal change = decimal.Parse(txtChange.Text)
int tenPenny = int.Parse(txt_BoxTenPenny.Text);
int totalTenPen = tenPenny - change / 10 ;
txt_BoxTenPenny.Text = totalTenPen.ToString();
Hope that helps!
Something like that:
decimal change = decimal.Parse(txtChange.Text)
if (change % 10 > 0)
{
int tenPenny = int.Parse(txt_BoxTenPenny.Text);
int totalTenPen = tenPenny - (change % 10);
txt_BoxTenPenny.Text = totalTenPen.ToString();
}
But is supposed that before that, you have added the 50p the users puts into machine in the txt_BoxTenPenny.
The modulo operator (%) returns the remainder of a division operation. For example, 23 MOD 10 = 3.
In this case I believe you want integer division, or the Floor. That is, you want to divide and throw away the remainder.
Since you are using decimal, I presume change will contain 0.10 for 10p. In that case, try the following:
//calculate the number of 10p coins you will get for change
var tenPenniesChange = (int)Math.Floor(change / 0.10m);
if(tenPenniesChange > 0)
txt_BoxTenPenny.Text = (int.Parse(txt_BoxTenPenny.Text) - tenPenniesChange).ToString();
change -= tenPenniesChange * 0.10;
Note the use of the Math.Floor function. If you had change = 0.13 you will get tenPenniesChange = 1. After the subtraction, you will then get change = 0.03.
This may be of some use:
Issuing vending machine change: Using C# to recursively build and search a tree

Calculating the percentage of uniqueness

I've figured out how to compare 2 text boxes and count how many words are the same in each one and how many are different but I was wondering instead of showing exactly how many are the same and how many are different could I calculate the percentage of difference between them?
For those who I confused, if i wrote this entire message again under this post and changed a few words and maybe removed some I could get feedback from the program telling me the difference is 14% or so...
You can get words by using string.Split:
String[] words1 = Textbox1.Text.Split();
String[] words2 = Textbox2.Text.Split();
You can use Linq to compare both:
var sameWordsInBoth = words1.Intersect(words2);
int count1 = sameWordsInBoth.Count();
var inTxt1ButNotInTxt2 = words1.Except(words2);
int count2 = inTxt1ButNotInTxt2.Count();
var inTxt2ButNotInTxt1 = words2.Except(words1);
int count3 = inTxt2ButNotInTxt1.Count();
To get the percentage you just have to count the total words(f.e. words1.Length) and compare that to the other counts.
For example:
double sameWordPercentage = (1.0 * count1 / words1.Length) * 100;
Since you said you already have the amount of unique words, and dont need explanation on how to get them:
double UniqueWordCount = 71;
double TotalWordCount = 231;
double Percentile = (UniqueWordCount/TotalWordCount)*100;
Answer : 30.7359.... %
If you want to round it
Math.Round(Percentile,2)
Answer : 30.74 %

C# format a double with ToString, and dispay zero value

I'm trying to find the best way to display a double in C# as follows:
7.345 should display as "73"
100.0 should display as "100"
0.234 shoud display as "02"
The input is a value between 0.00 and 10.00. I need to convert it to a filename. E.g. in case of a value of 5.4234, I should display "img54.jpg".
The problem is that I can't figure out how to display zero values in ToString() of doubles.
I tried this:
(10 * 7.345).ToString("##.") => correct
(10 * 10.00).ToString("##.") => correct
(10 * 0.000).ToString("##.") => FAIL, doesn't display anything.
(10 * 0.000).ToString("D2") => FAIL, D is not allowed in doubles
I can of course do some sophisticated string building, but if it's possible to use ToString, that would be much better of course.
Anyone an idea?
What do you want 0.00 to display as? "00"?
In that case you can try with format ToString("00.") instead.
Can you simply check if the double is 0? and If it is, set img00.jpg to your filename. That seems a lot easier than reworking your algorithm.
Why don't you convert it to an int?
int result = (int)(input * 10.00);
return result.ToString();
You could just convert to int before formatting like this:
((int)(10 * 7.345)).ToString("D2")
If you always have the input number of this format: #.###
You can multiply it by 1000 and divided by 100 and cast the result to an integer.
7.345 * 1000 = 7345 / 100 = 73.45 => Convert.ToInt32 => 73
0.000 * 1000 = 0 / 100 = 0 => Convert.ToInt32 = 0
Or you can multiply by 10 and convert to Integer.
return ((int)(input * 10.00)).ToString().SubString(0, 2);
double val = 7.345;
string result = val.ToString("0.#").Replace(".","");

Categories