round up given number in c# - c#

I want round up given numbers in c#
Ex:
round(25)=50
round(250) = 500
round(725) = 1000
round(1200) = 1500
round(7125) = 7500
round(8550) = 9000

Most of your data suggests that you want to round up to the nearest multiple of 500. This would be done by
int round(int input)
{
return (int)(500 * Math.Ceiling(input / 500.0));
}
The rounding of 25 to 50 will not work, though.
Another guess would be that you want your rounding to depend on the size of the number being rounded. The following function would round 25 to 50, 250 to 500, 0.025 to 0.05, and 2500 to 5000. Maybe you can work from there.
double round(double input)
{
double scale = Math.Floor(Math.Log10(input));
double step = 5 * Math.Pow(10, scale);
return step * Math.Ceiling(input/step);
}

Depending on what you need, this could be a nice, reusable solution.
static int RoundUpWeird(int rawNr)
{
if (rawNr < 100 && rawNr > -100)
return RoundUpToNext50(rawNr);
else
return RoundUpToNext500(rawNr);
}
static int RoundUpToNext50(int rawNr)
{
return RoundUpToNext(rawNr, 50);
}
static int RoundUpToNext500(int rawNr)
{
return RoundUpToNext(rawNr, 500);
}
static int RoundUpToNext(int rawNr, int next)
{
int result;
int remainder;
if ((remainder = rawNr % next) != 0)
{
if (rawNr >= 0)
result = RoundPositiveToNext(rawNr, next, remainder);
else
result = RoundNegativeToNext(rawNr, remainder);
if (result < rawNr)
throw new OverflowException("round(Number) > Int.MaxValue!");
return result;
}
return rawNr;
}
private static int RoundNegativeToNext(int rawNr, int remainder)
{
return rawNr - remainder;
}
private static int RoundPositiveToNext(int rawNr, int next, int remainder)
{
return rawNr + next - remainder;
}

This code should work according to the rules I can gather:
public static double Round(double val)
{
int baseNum = val <= 100 ? 100 : 1000;
double factor = 0.5;
double v = val / baseNum;
var res = Math.Ceiling(v / factor) / (1 / factor) * baseNum;
return res;
}

This should work. And also for numbers greater than those you wrote:
int round(int value)
{
int i = 1;
while (value > i)
{
i *= 10;
}
return (int)(0.05 * i * Math.Ceiling(value / (0.05 * i)));
}

Related

How to get amount into parts with nearest 100

I am using below code to divide amount into parts
public static IEnumerable<int> DistributeInteger(double total, int divider)
{
if (divider == 0)
{
yield return 0;
}
else
{
double rest = total % divider;
double result = total / (double)divider;
for (int i = 0; i < divider; i++)
{
if (rest-- > 0)
yield return (int)Math.Ceiling(result);
else
yield return (int)Math.Floor(result);
}
}
}
and using it as follows
var test = DistributeInteger(5000, 4).ToList();
above code returning me.
1250
1250
1250
1250
(All four part sum = 5000)
but i need it as nearest 100 of each part like
1300
1300
1300
1100
If I pass
var test = DistributeInteger(5219, 5).ToList();
then it is returning
1044
1044
1044
1044
1043
(All five part sum = 5219)
but it should be
1000
1000
1000
1000
1000
219
if amount 1 to 100 for example 89 then it will return same amount which is 89,
I am trying it from morning but no luck.
as well as i checked may codes from net but it is giving only solution to get nearest 100 value of a given no.
How about this?
public static IEnumerable<int> DistributeInteger(double total, int divider)
{
int part = 100 * ((int)(50 + total / divider) / 100);
if (part == 0)
{
yield return (int)total;
yield break;
}
double runningTotal = 0;
while (runningTotal <= (total - part))
{
yield return part;
runningTotal += part;
}
if (runningTotal < total)
yield return (int) (total - runningTotal);
}
(Note: Error handling omitted for brevity.)
How about:
public static IEnumerable<int> DistributeInteger(double total, int divider)
{
// get increment to the nearest hundred
var increment = (int) Math.Round(total/ 100 / divider, MidpointRounding.AwayFromZero) * 100;
// make sure increment is non-zero
if (increment == 0) increment = 100;
var remainder = (int) total;
// subtract increment while remainder is >= zero
while (remainder >= increment){
remainder -= increment;
yield return increment;
}
// check if remainder is non-zero
if (remainder > 0)
yield return remainder;
}
Now uses Ceiling
Seems to work with midpoint rounding away from zero
What about this approach:
public static IEnumerable<int> DistributeInteger(double total, int divider)
{
if (divider == 0)
{
return null;
}
else
{
var parts = new List<int>();
var singlePart = total / divider;
singlePart = Math.Round(singlePart / 100, MidpointRounding.AwayFromZero) * 100;
while (total - singlePart > 0)
{
parts.Add((int)singlePart);
total -= singlePart;
}
// Add remainnig value.
parts.Add((int)total);
return parts;
}
}
It will work for second scenario only, for the first scenarion you'd need to use Ceiling function instead of Round.

Find the min and max for quadratic equation

how to find the min and max for quadratic equation using c# ??
f(x,y) = x^2 + y^2 + 25 * (sin(x)^2 + sin(y)^2) ,where (x,y) from (-2Pi, 2Pi) ??
in the manual solving I got min is = 0 , max = 8Pi^2 = 78.957 .
I tried to write the code based on liner quadratic code but something goes totally wrong
this code give the min = -4.?? and the max = 96 could you help to know where is my mistake please ??
I uploaded the code to dropbox if anyone can have look : https://www.dropbox.com/s/p7y6krk2gk29i9e/Program.cs
double[] X, Y, Result; // Range array and result array.
private void BtnRun_Click(object sender, EventArgs e)
{
//Set any Range for the function
X = setRange(-2 * Math.PI, 2 * Math.PI, 10000);
Y = setRange(-2 * Math.PI, 2 * Math.PI, 10000);
Result = getOutput_twoVariablesFunction(X, Y);
int MaxIndex = getMaxIndex(Result);
int MinIndex = getMinIndex(Result);
TxtMin.Text = Result[MinIndex].ToString();
TxtMax.Text = Result[MaxIndex].ToString();
}
private double twoVariablesFunction(double x,double y)
{
double f;
//Set any two variables function
f = Math.Pow(x, 2) + Math.Pow(y, 2) + 25 * (Math.Pow(Math.Sin(x), 2) + Math.Pow(Math.Sin(y), 2));
return f;
}
private double[] setRange(double Start, double End, int Sample)
{
double Step = (End - Start) / Sample;
double CurrentVaue = Start;
double[] Array = new double[Sample];
for (int Index = 0; Index < Sample; Index++)
{
Array[Index] = CurrentVaue;
CurrentVaue += Step;
}
return Array;
}
private double[] getOutput_twoVariablesFunction(double[] X, double[] Y)
{
int Step = X.Length;
double[] Array = new double[Step];
for (int Index = 0; Index < X.Length ; Index++)
{
Array[Index] = twoVariablesFunction(X[Index], Y[Index]);
}
return Array;
}
private int getMaxIndex(double[] ValuesArray)
{
double M = ValuesArray.Max();
int Index = ValuesArray.ToList().IndexOf(M);
return Index;
}
private int getMinIndex(double[] ValuesArray)
{
double M = ValuesArray.Min();
int Index = ValuesArray.ToList().IndexOf(M);
return Index;
}
Do you want to compute (sin(x))^2 or sin(x^2)? In your f(x,y) formula it looks like (sin(x))^2, but in your method twoVariablesFunction like sin(x^2).

Truncate decimals beyond first positive

C# - truncate decimals beyond first positive
a number is 0.009012
result should be 0.009
or is 1.1234 and 'd be 1.1
or 2.099 ~ 2.09
and so on
in a fast and optimum way
Think mathematically, use logarithmus with base 10
this function will just take the first cipher
public double RoundOnFirstDecimal(double number)
{
int shift = -1 * ((int)Math.Floor(Math.Log10(number)));
return Math.Floor(number * Math.Pow(10, shift)) / Math.Pow(10, shift);
}
But you want to have it this way: (will shift only regarding the decimal fractions, but not full numbers)
public double RoundOnFirstDecimal(double number)
{
int shift = -1 * ((int)Math.Floor(Math.Log10(number % 1)));
return Math.Floor(number % 1 * Math.Pow(10, shift)) / Math.Pow(10, shift) + number - number % 1;
}
thats gonna be significantly faster than any regex or looping
Try this method:
private static string RoundSpecial(double x)
{
string s = x.ToString();
int dotPos = s.IndexOf('.');
if (dotPos != -1)
{
int notZeroPos = s.IndexOfAny(new[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' }, dotPos + 1);
return notZeroPos == -1 ? s : s.Substring(0, notZeroPos + 1);
}
return s;
}
I'm not sure that it is the fastest and optimal method, but it does what you want.
Second approach is to use Log10 and %:
private static double RoundSpecial(double x)
{
int pos = -(int)Math.Log10(x - (int)x);
return Math.Round(x - (x % Math.Pow(0.1, pos + 1)), pos + 1);
}
You may try regular expression too:
decimal d = 2.0012m;
Regex pattern = new Regex(#"^(?<num>(0*[1-9]))\d*$");
Match match = pattern.Match(d.ToString().Split('.')[1]);
string afterDecimal = match.Groups["num"].Value; //afterDecimal = 001
Here's a solution that uses math instead of string logic:
double nr = 0.009012;
var partAfterDecimal = nr - (int) nr;
var partBeforeDecimal = (int) nr;
int count = 1;
partAfterDecimal*=10;
int number = (int)(partAfterDecimal);
while(number == 0)
{
partAfterDecimal *= 10;
number = (int)(partAfterDecimal);
count++;
}
double dNumber = number;
while(count > 0){
dNumber /= 10.0;
count--;
}
double result = (double)partBeforeDecimal + dNumber;
result.Dump();
if you don't want to use the Math library:
static double truncateMyWay(double x)
{
double afterDecimalPoint = x - (int)x;
if (afterDecimalPoint == 0.0) return x;
else
{
int i = 0;
int count10 = 1;
do
{
afterDecimalPoint *= 10;
count10 *= 10;
i++;
} while ((int) afterDecimalPoint == 0);
return ((int)(x * count10))/((double)count10);
}
}
Happy Codding! ;-)

Good implementation of a Change Calculator in C#

Given an amount in ml and 3 pack sizes (20ml, 200ml and 1000ml) I'd like to calculate how many of each packs are needed to fulfill the total amount.
E.g.
Amount = 3210ml
1000ml = 3 packs
200ml = 1 pack
20ml = 1 pack (always round up to nearest quantity)
This is pretty much just like a change calculator, and I'm looking for the right way to do it.
Here's my attempt
public class PackSizeCalculator
{
private const int LargePackSize = 1000;
private const int MediumPackSize = 200;
private const int SmallPackSize = 20;
public int LargePacks {get; set;}
public int MediumPacks {get; set;}
public int SmallPacks {get; set;}
public PackSizeCalculator(int amount)
{
int remainder = amount;
while(remainder > 0) {
if(remainder >= LargePackSize)
{
LargePacks = remainder / LargePackSize;
remainder = remainder % LargePackSize;
}
else if(remainder >= MediumPackSize)
{
MediumPacks = remainder / MediumPackSize;
remainder = remainder % MediumPackSize;
}
else if(remainder > SmallPackSize)
{
if(remainder % SmallPackSize == 0)
{
SmallPacks = (remainder / SmallPackSize);
}
else {
SmallPacks = (remainder / SmallPackSize) + 1;
}
remainder = 0;
}
else {
SmallPacks = 1;
remainder = 0;
}
}
}
}
Is this a good way to go about it or would you recommend something different?
Something like this:
const int LARGE_PACK = 1000;
const int MEDIUM_PACK = 200;
const int SMALL_PACK = 20;
int largePacks = (int)(Amount / LARGE_PACK);
int mediumPacks = (int)((Amount % LARGE_PACK) / MEDIUM_PACK);
int smallPacks = (int)ceil(((float)((Amount % LARGE_PACK) % MEDIUM_PACK) / SMALL_PACK));
You can create a function like this:
struct Change
{
public int Large;
public int Medium;
public int Small;
}
private Change CalculateChange(int TotalAmount)
{
Change result;
result.Large = TotalAmount >= 1000 ? TotalAmount / 1000 : 0;
result.Medium = TotalAmount % 1000 >= 200 ? (TotalAmount % 1000) / 200 : 0;
result.Small = (TotalAmount % 1000) % 200 >= 20 ? ((TotalAmount % 1000) % 200) / 20 : 0;
return result;
}
At the end you will have your result of Change struct Type.

Round any n-digit number to (n-1) zero-digits

Sorry hard to formulate.
I need to round like this:
12 -> 10
152 -> 200
1538 -> 2000
25000 -> 30000
etc.
Twisting my head, but can't see how to make this. Must work for any n number of digits. Anyone got an elegant method for it?
c# or vb.net
How about this:
double num = 152;
int pow = (int)Math.Log10(num);
int factor = (int)Math.Pow(10, pow);
double temp = num / factor;
double result = Math.Round(temp) * factor;
I think you should try with something like this:
public int Round( int number)
{
int power = number.ToString().Length - 1;
int sz = Math.Pow(10, power);
int rounded = (int)Math.Round( number / sz );
return rounded * sz;
}
The idea is to get the size of the nearest 10 power, available by the length of the number expressed as a string. Then divide the number by that power, leaving it like 1,2 and then round it using the Math.Round method and restore the size by remultiplying it to the power.
Much like the previous answer...
I would do it this way:
double d = 25000;
int power = d.ToString().Length - 1;
double multipler = Math.Pow(10,power);
d = Math.Round(d / multipler) * multipler;
Console.WriteLine(d);
One of the way could be
Convert the number to Decimal
Divide it by 10^(n-1) (where n is number of digits)
Now use round function (Decimal.Round)
Multiply again by 10^(n-1)
Divide the number by 10n and round the result, then multiply the result back with 10n;
int MyRound(int num)
{
double divisor = Math.Pow(10, num.ToString().Length - 1);
return (int)(Math.Round(num / divisor, MidpointRounding.AwayFromZero) * divisor);
}
Note that we should use MidpointRounding.AwayFromZero when rounding because of the default banker's rounding.
int MakeOneSigFig(int value)
{
int neg = 1;
if(value <= 10 && value >= -10) { return value; }
if(value == int.MinValue) { value = int.MaxValue; neg = -1; }
if(value < 0) { value = -value; neg = -1; }
int mult = 10; // start at 10 because we've got 'firstDigit = value / 10' below
while(value > 99) { value /= 10; mult *= 10; }
int firstDigit = value / 10;
if(value % 10 >= 5) firstDigit++;
return neg * firstDigit * mult;
}
This is equivalent to MidpointRounding.AwayFromZero. This method doesn't do any double math or string conversions. If you didn't want to loop, you could replace that with the if block below. That would be more efficient, but more code and not quite as easy to read.
if(value < 100) { mult = 10; }
else if(value < 1000) { mult = 100; value /= 10; }
else if(value < 10000) { mult = 1000; value /= 100; }
else if(value < 100000) { mult = 10000; value /= 1000; }
// etc.

Categories

Resources