Rounding to the nearest number ending in 9 - c#

I have a website that calculates the price of bus tickets. Currently the price is rounded to the nearest 10, but now I want the calculated price to be rounded to the nearest number ending in 9.
EDIT: Added new examples answering question from the comments.
Examples:
770 to 774 should be rounded to 769
775 to 784 should be rounded to 779
785 to 790 should be rounded to 789
Does anybody have any tips on how I can solve my problem using c#?

Round to the nearest 10 and then subtract 1.
In c#, you can do it like this :
double val = 444.3;
double step1 = val/10; // 44.43
double step2 = Math.Round(step1, MidpointRounding.AwayFromZero); // 44
int step3 = (int)step2 * 10; // 440
int rndVal = step3 - 1; // rndVal == 439
or the shortest version :
double val = 444.3;
int rndVal = (int)(Math.Round(val/10, MidpointRounding.AwayFromZero)*10)-1;

Add 1, round to nearest 10 and then subtract 1.

The function below will do the job.
public static int RoundTo9(double value)
{
return (int)(value/10.0 + 0.5) * 10 - 1;
}

int number=65;
// Console.WriteLine(number);
int lastNumber=number%10;
//Console.WriteLine(lastNumber);
if(lastNumber<5)
{
number-=lastNumber;
number--;
Console.WriteLine(number);
}
else
{
var addNumber=10-lastNumber;
number+=addNumber;
number--;
Console.WriteLine(number);
}

Related

C# round a double to the first decimal place that makes sense [duplicate]

This question already has answers here:
Round a decimal number to the first decimal position that is not zero
(5 answers)
Closed 2 years ago.
I have an overloaded extension method which rounds either a decimal or double to N number of decimal places and it works perfectly.
public static class NumberExtensions
{
public static string ToStringNDecimalPlaces(this double dbValue, int nDecimal)
{
return dbValue.ToString("N" + nDecimal);
}
public static string ToStringNDecimalPlaces(this decimal dbValue, int nDecimal)
{
return dbValue.ToString("N" + nDecimal);
}
}
My question is, I want to create another called something like, "ToStringFirstDecimalPlace" or something like that which takes the decimal value and rounds it to the first logical decimal value after the 0s. Let me give some, this is how I would like the method to work:
e.g.
0.000345879 = 0.0003
0.019356 = 0.02
0.1 = 0.1
So it ignores the leading 0s and takes the nth to be the first logical number that makes sense instead of just rounding to 0.0 for example.
Well can't you count the number of zeroes and then format accordingly?
Example for positive values:
string result;
if(dbValue != 0)
{
int count = 0;
var copyDb = dbValue;
while(copyDb < 1)
{
copyDb *= 10;
count++;
}
result = dbValue.ToStringNDecimalPlaces(count);
}
else
{
result = "0";
}
You can write the following function to achieve this:
public static string ToStringNDecimalPlacesIgnoreZeros(this double dbValue)
{
var value = dbValue - Math.Floor(dbValue); // Get rid of integer digits
int position = 0;
while (value > 0 && Math.Floor(value) == 0)
{
value = value * 10;
position += 1;
}
if (value == 0)
return dbValue.ToString("N");
else
return dbValue.ToStringNDecimalPlaces( position);
}
First, assume that the input is between 0 and 1, inclusive. If not, subtract the integer part (and if negative, negate the remainder) before rounding the rest (this process can be reversed after the rounding is complete). Then, do something like this:
RountToFirstLogical(input)
1. place = 1
2. while place > input
3. place = place / 10
4. input = round(input/place) * place
5. return input
Examples:
input=0.000345879
place=1, 0.1, 0.01, 0.001, 0.0001
input/place = 3.45879
round(input/place) = 3
round(input/place) * place = 0.0003
input=0.019356
place=1, 0.1, 0.01
input/place = 1.9356
round(input/place) = 2
round(input/place)*place = 0.02
input=0.1
place=1, 0.1
input/place=1
round(input/place)=1
round(input/place)*place=0.1

rounded to the nearest 10's place in c#

I want to The numbers are being rounded to the nearest 10's place.
For example, a number like 17.3 is being rounded to 20.0. and want to be allow three significant digits. Meaning for round to the nearest tenth of a percent as the last step of the process.
Sample :
the number is 17.3 ,i want round to 20 ,
and this number is 13.3 , i want round to 10 ?
How can i do this ?
Chris Charabaruk gives you your desired answer here
To get to the core, here is his solution as an extension method:
public static class ExtensionMethods
{
public static int RoundOff (this int i)
{
return ((int)Math.Round(i / 10.0)) * 10;
}
}
int roundedNumber = 236.RoundOff(); // returns 240
int roundedNumber2 = 11.RoundOff(); // returns 10
//edit:
This method only works for int values. You'd have to edit this method to your liking.
f.e.:
public static class ExtensionMethods
{
public static double RoundOff (this double i)
{
return (Math.Round(i / 10.0)) * 10;
}
}
/edit2: As corak stated you should/could use
Math.Round(value / 10, MidpointRounding.AwayFromZero) * 10
Other answers are correct also, but here's how you'd do it without Math.Round:
((int)((17.3 + 5) / 10)) * 10 // = 20
((int)((13.3 + 5) / 10)) * 10 // = 10
((int)((15.0 + 5) / 10)) * 10 // = 20
Try this-
double d1 = 17.3;
int rounded1 = ((int)Math.Round(d/10.0)) * 10; // Output is 20
double d2 = 13.3;
int rounded2 = ((int)Math.Round(d/10.0)) * 10; // Output is 10
double Num = 16.6;
int intRoundNum = (Convert.ToInt32(Math.Round(Num / 10)) * 10);
Console.WriteLine(intRoundNum);
If you want to avoid casting or pulling in the math library you could also use the modulus operator and do something like the following:
int result = number - (number % 10);
if (number % 10 >= 5)
{
result += 10;
}
For your given numbers:
number
processing
result
13.3
13.3 - (3.3)
10
17.3
17.3 - (7.3) + 10
20

Split double into two int, one int before decimal point and one after

I need to split an double value, into two int value, one before the decimal point and one after. The int after the decimal point should have two digits.
Example:
10.50 = 10 and 50
10.45 = 10 and 45
10.5 = 10 and 50
This is how you could do it:
string s = inputValue.ToString("0.00", CultureInfo.InvariantCulture);
string[] parts = s.Split('.');
int i1 = int.Parse(parts[0]);
int i2 = int.Parse(parts[1]);
Manipulating strings can be slow. Try using the following:
double number;
long intPart = (long) number;
double fractionalPart = number - intPart;
What programming language you want to use to do this? Most of the language should have a Modulo operator. C++ example:
double num = 10.5;
int remainder = num % 1
"10.50".Split('.').Select(int.Parse);
/// <summary>
/// Get the integral and floating point portions of a Double
/// as separate integer values, where the floating point value is
/// raised to the specified power of ten, given by 'places'.
/// </summary>
public static void Split(Double value, Int32 places, out Int32 left, out Int32 right)
{
left = (Int32)Math.Truncate(value);
right = (Int32)((value - left) * Math.Pow(10, places));
}
public static void Split(Double value, out Int32 left, out Int32 right)
{
Split(value, 1, out left, out right);
}
Usage:
Int32 left, right;
Split(10.50, out left, out right);
// left == 10
// right == 5
Split(10.50, 2, out left, out right);
// left == 10
// right == 50
Split(10.50, 5, out left, out right);
// left == 10
// right == 50000
how about?
var n = 1004.522
var a = Math.Floor(n);
var b = n - a;
Another variation that doesn't involve string manipulation:
static void Main(string[] args)
{
decimal number = 10123.51m;
int whole = (int)number;
decimal precision = (number - whole) * 100;
Console.WriteLine(number);
Console.WriteLine(whole);
Console.WriteLine("{0} and {1}",whole,(int) precision);
Console.Read();
}
Make sure they're decimals or you get the usual strange float/double behaviour.
you can split with string and then convert into int ...
string s = input.ToString();
string[] parts = s.Split('.');
This function will take time in decimal and converts back into base 60 .
public string Time_In_Absolute(double time)
{
time = Math.Round(time, 2);
string[] timeparts = time.ToString().Split('.');
timeparts[1] = "." + timeparts[1];
double Minutes = double.Parse(timeparts[1]);
Minutes = Math.Round(Minutes, 2);
Minutes = Minutes * (double)60;
return string.Format("{0:00}:{1:00}",timeparts[0],Minutes);
//return Hours.ToString() + ":" + Math.Round(Minutes,0).ToString();
}
Try:
string s = "10.5";
string[] s1 = s.Split(new char[] { "." });
string first = s1[0];
string second = s1[1];
You can do it without going through strings. Example:
foreach (double x in new double[]{10.45, 10.50, 10.999, -10.323, -10.326, 10}){
int i = (int)Math.Truncate(x);
int f = (int)Math.Round(100*Math.Abs(x-i));
if (f==100){ f=0; i+=(x<0)?-1:1; }
Console.WriteLine("("+i+", "+f+")");
}
Output:
(10, 45)
(10, 50)
(11, 0)
(-10, 32)
(-10, 33)
(10, 0)
Won't work for a number like -0.123, though. Then again, I'm not sure how it would fit your representation.
I actually just had to answer this in the real world and while #David Samuel's answer did part of it here is the resulting code I used. As said before Strings are way too much overhead. I had to do this calculation across pixel values in a video and was still able to maintain 30fps on a moderate computer.
double number = 4140 / 640; //result is 6.46875 for example
int intPart = (int)number; //just convert to int, loose the dec.
int fractionalPart = (int)((position - intPart) * 1000); //rounding was not needed.
//this procedure will create two variables used to extract [iii*].[iii]* from iii*.iii*
This was used to solve x,y from pixel count in 640 X 480 video feed.
Console.Write("Enter the amount of money: ");
double value = double.Parse(Console.ReadLine());
int wholeDigits = (int) value;
double fractionalDigits = (value - wholeDigits) * 100;
fractionalDigits = (int) fractionalDigits;
Console.WriteLine(
"The number of the shekels is {0}, and the number of the agurot is {1}",
wholeDigits, fractionalDigits);
Using Linq. Just clarification of #Denis answer.
var parts = "10.50".Split('.').Select(int.Parse);
int i1 = parts.ElementAt(0);
int i2 = parts.ElementAt(1);

How do I round to the nearest 0.5?

I have to display ratings and for that, I need increments as follows:
Input
Rounded
1.0
1
1.1
1
1.2
1
1.3
1.5
1.4
1.5
1.5
1.5
1.6
1.5
1.7
1.5
1.8
2.0
1.9
2.0
2.0
2.0
2.1
2.0
and so on...
Is there a simple way to compute the required values?
Multiply your rating by 2, then round using Math.Round(rating, MidpointRounding.AwayFromZero), then divide that value by 2.
Math.Round(value * 2, MidpointRounding.AwayFromZero) / 2
Multiply by 2, round, then divide by 2
if you want nearest quarter, multiply by 4, divide by 4, etc
Here are a couple of methods I wrote that will always round up or down to any value.
public static Double RoundUpToNearest(Double passednumber, Double roundto)
{
// 105.5 up to nearest 1 = 106
// 105.5 up to nearest 10 = 110
// 105.5 up to nearest 7 = 112
// 105.5 up to nearest 100 = 200
// 105.5 up to nearest 0.2 = 105.6
// 105.5 up to nearest 0.3 = 105.6
//if no rounto then just pass original number back
if (roundto == 0)
{
return passednumber;
}
else
{
return Math.Ceiling(passednumber / roundto) * roundto;
}
}
public static Double RoundDownToNearest(Double passednumber, Double roundto)
{
// 105.5 down to nearest 1 = 105
// 105.5 down to nearest 10 = 100
// 105.5 down to nearest 7 = 105
// 105.5 down to nearest 100 = 100
// 105.5 down to nearest 0.2 = 105.4
// 105.5 down to nearest 0.3 = 105.3
//if no rounto then just pass original number back
if (roundto == 0)
{
return passednumber;
}
else
{
return Math.Floor(passednumber / roundto) * roundto;
}
}
There are several options. If performance is a concern, test them to see which works fastest in a large loop.
double Adjust(double input)
{
double whole = Math.Truncate(input);
double remainder = input - whole;
if (remainder < 0.3)
{
remainder = 0;
}
else if (remainder < 0.8)
{
remainder = 0.5;
}
else
{
remainder = 1;
}
return whole + remainder;
}
decimal d = // your number..
decimal t = d - Math.Floor(d);
if(t >= 0.3d && t <= 0.7d)
{
return Math.Floor(d) + 0.5d;
}
else if(t>0.7d)
return Math.Ceil(d);
return Math.Floor(d);
Sounds like you need to round to the nearest 0.5. I see no version of round in the C# API that does this (one version takes a number of decimal digits to round to, which isn't the same thing).
Assuming you only have to deal with integer numbers of tenths, it's sufficient to calculate round (num * 2) / 2. If you're using arbitrarily precise decimals, it gets trickier. Let's hope you don't.
These lines of code snap a float dx to nearest snap:
if (snap <= 1f)
dx = Mathf.Floor(dx) + (Mathf.Round((dx - Mathf.Floor(dx)) * (1f / snap)) * snap);
else
dx = Mathf.Round(dx / snap) * snap;
So if snap is 0.5, value gets rounded to nearest 0.5 value (1.37 goes to 1.5), if it is 0.02, value is rounded to nearest 0.02 ((1.37 goes to 1.38)). If snap is 3, value is rounded to nearest 3 (7.4 goes to 6, 7.6 goes to 9) etc... I use it to quickly snap objects on scene in unity because unity default snapping doesn't seem to work well for me.
Public Function Round(ByVal text As TextBox) As Integer
Dim r As String = Nothing
If text.TextLength > 3 Then
Dim Last3 As String = (text.Text.Substring(text.Text.Length - 3))
If Last3.Substring(0, 1) = "." Then
Dim dimcalvalue As String = Last3.Substring(Last3.Length - 2)
If Val(dimcalvalue) >= 50 Then
text.Text = Val(text.Text) - Val(Last3)
text.Text = Val(text.Text) + 1
ElseIf Val(dimcalvalue) < 50 Then
text.Text = Val(text.Text) - Val(Last3)
End If
End If
End If
Return r
End Function
This answer is taken from Rosdi Kasim's comment in the answer that John Rasch provided.
John's answer works but does have an overflow possibility.
Here is my version of Rosdi's code:
I also put it in an extension to make it easy to use. The extension is not necessary and could be used as a function without issue.
<Extension>
Public Function ToHalf(value As Decimal) As Decimal
Dim integerPart = Decimal.Truncate(value)
Dim fractionPart = value - Decimal.Truncate(integerPart)
Dim roundedFractionPart = Math.Round(fractionPart * 2, MidpointRounding.AwayFromZero) / 2
Dim newValue = integerPart + roundedFractionPart
Return newValue
End Function
The usage would then be:
Dim newValue = CDec(1.26).ToHalf
This would return 1.5
I had difficulty with this problem as well.
I code mainly in Actionscript 3.0 which is base coding for the Adobe Flash Platform, but there are simularities in the Languages:
The solution I came up with is the following:
//Code for Rounding to the nearest 0.05
var r:Number = Math.random() * 10; // NUMBER - Input Your Number here
var n:int = r * 10; // INTEGER - Shift Decimal 2 places to right
var f:int = Math.round(r * 10 - n) * 5;// INTEGER - Test 1 or 0 then convert to 5
var d:Number = (n + (f / 10)) / 10; // NUMBER - Re-assemble the number
trace("ORG No: " + r);
trace("NEW No: " + d);
Thats pretty much it.
Note the use of 'Numbers' and 'Integers' and the way they are processed.
Good Luck!

C# Formula to distribute numbers

I'm looking for a formula that can spread out numbers in a linear format based on a minimum number, max number and amount of numbers (or dots) between. The catch is, the closer you get to the max, the more numbers should be there.
An example (number will vary and will be about 100 times larger)
Min = 0
Max = 16
AmountOfNumbersToSpread = 6
0 1 2 3 4 5 6 7 8 9 A B C D E F
1 2 3 4 5 6
Thanks for the help in advance.
Based on the answer of Tal Pressman, you can write a distribution function like this:
IEnumerable<double> Spread(int min, int max, int count, Func<double, double> distribution)
{
double start = min;
double scale = max - min;
foreach (double offset in Redistribute(count, distribution))
yield return start + offset * scale;
}
IEnumerable<double> Redistribute(int count, Func<double, double> distribution)
{
double step = 1.0 / (count - 1);
for (int i = 0; i < count; i++)
yield return distribution(i * step);
}
You can use any kind of distribution function which maps [0;1] to [0;1] this way. Examples:
quadratic
Spread(0, 16, 6, x => 1-(1-x)*(1-x))
Output: 0 5.76 10.24 13.44 15.36 16
sine
Spread(0, 16, 6, x => Math.Sin(x * Math.PI / 2))
Output: 0 4.94427190999916 9.40456403667957 12.9442719099992 15.2169042607225 16
Basically, you should have something that looks like:
Generate a random number between 0 and 1.
Implement your desired distribution function (a 1:1 function from [0,1]->[0,1]).
Scale the result of the distribution function to match your desired range.
The exact function used for the second point is determined according to how exactly you want the numbers to be distributed, but according to your requirement, you'll want a function that has more values close to 1 than 0. For example, a sin or cos function.
Tried this on paper and it worked:
given MIN, MAX, AMOUNT:
Length = MAX - MIN
"mark" MIN and MAX
Length--, AMOUNT--
Current = MIN
While AMOUNT > 1
Space = Ceil(Length * Amount / (MAX - MIN))
Current += Space
"mark" Current
By "mark" I mean select that number, or whatever you need to do with it.
Close answer, not quite though, needs to work for larger numbers.
List<int> lstMin = new List<int>();
int Min = 1;
int Max = 1500;
int Length = Max - Min;
int Current = Min;
int ConnectedClient = 7;
double Space;
while(ConnectedClient > 0)
{
Space = Math.Ceiling((double)(Length * ConnectedClient / (Max - Min)));
Current += (int)Space;
ConnectedClient--;
Length--;
lstMin.Add(Current);
}

Categories