My scenario is that if
47/15= 3.13333
i want to convert it into 4, if the result has decimal i want to increase the result by 1, right now i am doing this like
float res = ((float)(62-15) / 15);
if (res.ToString().Contains("."))
{
string digit=res.ToString().Substring(0, res.ToString().IndexOf('.'));
int incrementDigit=Convert.ToInt16(k) + 1;
}
I want to know is there any shortcut way or built in function in c# so that i can do this fast without implementing string functions.
Thanks a lot.
Do you mean you want to perform integer division, but always rounding up? I suspect you want:
public static int DivideByFifteenRoundingUp(int value) {
return (value + 14) / 15;
}
This avoids using floating point arithmetic at all - it just allows any value which isn't an exact multiple of 15 to be rounded up, due to the way that integer arithmetic truncates towards zero.
Note that this does not work for negative input - for example, if you passed in -15 this would return 0. you could fix this with:
public static int DivideByFifteenRoundingUp(int value) {
return value < 0 ? value / 15 : (value + 14) / 15;
}
Use Math.Ceiling Quoting MSDN:
Returns the smallest integral value that is greater than or equal to
the specified decimal number.
You are looking for Math.Ceiling().
Convert the value you have to a Decimal or Double and the result of that method is what you need. Like:
double number = ((double)(62-15) / (double)15);
double result = Math.Ceiling(number);
Note the fact that I cast 15 to a double, so I avoid integer division. That is most likely not what you want here.
Another way of doing what you ask is to add 0.5 to every number, then floor it (truncate the decimal places). I'm afraid I don't have access to a C# compiler right now to confirm the exact function calls!
NB: But as others have confirmed, I would think the Math.Ceiling function best communicates to others what you intend.
Something like:
float res = ((float)(62-15) / 15);
int incrementDigit = (int)Math.Ceiling(res);
or
int incrementDigit = (int)(res + 0.5f);
Related
Calling ToString() on imprecise floats produces numbers a human would expect (eg. 4.999999... gets printed as 5). However, when casting to int, the fractional part gets dropped and the result is an integer decremented by 1.
float num = 5f;
num *= 0.01f;
num *= 100f;
num.ToString().Dump(); // produces "5", as expected
((int)num).ToString().Dump(); // produces "4"
How do I cast the float to int, so that I get the human friendly value, that float.ToString() produces?
I'm using this dirty hack:
int ToInt(float value) {
return (int)(value + Math.Sign(value) * 0.00001);
}
..but surely there must be a more elegant solution.
Edit: I'm well aware of the reasons why floats are truncated the way they are (4.999... to 4, etc.) The question is about casting to int while emulating the default behavior of System.Single.ToString()
To better illustrate the behavior I'm looking for:
-4.99f should be cast to -4
4.01f should be cast to 4
4.99f should be cast to 4
4.999999f should be cast to 4
4.9999993f should be cast to 5
This is the exact same behavior that ToString produces.
Try running this:
float almost5 = 4.9999993f;
Console.WriteLine(almost5); // "5"
Console.WriteLine((int)almost5); // "4"
Maybe you are looking for this:
Convert.ToInt32(float)
source
0.05f * 100 is not exactly 5 due to floating point rounding (it's actually the value 4.999998.... when expressed as a float
The answer is that in the case of (int)(.05f * 100), you are taking the float value 4.999998 and truncating it to an integer, which yields 4.
So use Math.Round. The Math.Round function rounds a float value to the nearest integer, and rounds midpoint values to the nearest even number.
float num = 5f;
num *= 0.01f;
num *= 100f;
Console.WriteLine(num.ToString());
Console.WriteLine(((int)Math.Round(num)).ToString());
So far the best solution seems to be the one from the question.
int ToInt(float value) {
return (int)(value + Math.Sign(value) * 0.000001f);
}
This effectively snaps the value to the closest int, if the difference is small enough (less than 0.000001). However, this function differs from ToString's behavior and is slightly more tolerant to imprecisions.
Another solution, suggested by #chux is to use ToString and parse the string back. Using Int32.Parse throws an exception when a number has a decimal point (or a comma), so you have to keep only the integer part of the string and it may cause other troubles depending on your default CultureInfo.
I wonder why my next statement always returns 1, and how I can fix it. I accounted for integer division by casting the first element in the division to float. Apart from that I'm not getting much further.
int value = any int;
float test = (float)value / int.MaxValue / 2 + 1;
By the way my intention is to make this convert ANY integer to a 0-1 float
To rescale a number in the range s..e to 0..1, you do (value-s)/(e-s).
So in this case:
double d = ((double)value - int.MinValue) / ((double)int.MaxValue - int.MinValue);
float test = (float)d;
It doesn't always return zero. For example, this code:
int value = 12345678;
float test = (float)value / int.MaxValue / 2 + 1;
Console.WriteLine(test);
Prints 1.002874
The problem is that floats are not very precise, so for small values of value, the result will be 0 to the number of digits of precision that floats can handle.
For example, value == 2300 will print 0, but value == 2400 will print 1.000001.
If you use double you get better results:
int value = 1;
double test = (double)value / int.MaxValue / 2 + 1;
Console.WriteLine(test);
Prints 1.00000000023283
Avoid implicit type conversions. Use all elements in your expression of type double, if that is the type you want. Convert the int.MaxValue and the 2 to double before using them in the division, so that no implicit type conversions are involved.
Also, you might want to parenthesize your expression to make it more readable. As it is, it is error prone.
Finally, if your expression is too complex and you don't know what's going on, split it into simpler expressions, all of them of type double.
P.S.: By the way, trying to get precise results and using float instead of double is not a very wise thing to do. Use float for precise floating point calculations.
I have been searching forever and I simply cannot find the answer, none of them will work properly.
I want to turn a double like 0.33333333333 into 0,33 or 0.6666666666 into 0,66
Number like 0.9999999999 should become 1 though.
I tried various methods like
value.ToString("##.##", System.Globalization.CultureInfo.InvariantCulture)
It just returns garbage or rounds the number wrongly.
Any help please?
Basically every number is divided by 9, then it needs to be displayed with 2 decimal places without any rounding.
I have found a nice function that seems to work well with numbers up to 9.999999999
Beyond that it starts to lose one decimal number. With a number like 200.33333333333
its going to just display 200 instead of 200,33. Any fix for that guys?
Here it is:
string Truncate(double value, int precision)
{
string result = value.ToString();
int dot = result.IndexOf(',');
if (dot < 0)
{
return result;
}
int newLength = dot + precision + 1;
if (newLength == dot + 1)
{
newLength--;
}
if (newLength > result.Length)
{
newLength = result.Length;
}
return result.Substring(0, newLength);
}
Have you tried
Math.Round(0.33333333333, 2);
Update*
If you don't want the decimal rounded another thing you can do is change the double to a string and then get get a substring to two decimal places and convert it back to a double.
doubleString = double.toString();
if(doubleString.IndexOf(',') > -1)
{
doubleString = doubleString.Substring(0,doubleString.IndexOf(',')+3);
}
double = Convert.ToDouble(doubleString);
You can use a if statement to check for .99 and change it to 1 for that case.
Math.Truncate(value * 100)/100
Although I make no guarantees about how the division will affect the floating point number. Decimal numbers can often not be represented exactly in floating point, because they are stored as base 2, not base 10, so if you want to guarantee reliability, use a decimal, not a double.
Math.Round((decimal)number, 2)
Casting to a decimal first will avoid the precision issues discussed on the documentation page.
Math.Floor effectively drops anything after the decimal point. If you want to save two digits, do the glitch operation - multiply then divide:
Math.Floor(100 * number) / 100
This is faster and safer than doing a culture-dependent search for a comma in a double-converted-to-string, as accepted answer suggests.
you can try one from below.there are many way for this.
1.
value=Math.Round(123.4567, 2, MidpointRounding.AwayFromZero) //"123.46"
2.
inputvalue=Math.Round(123.4567, 2) //"123.46"
3.
String.Format("{0:0.00}", 123.4567); // "123.46"
4.
string.Format("{0:F2}", 123.456789); //123.46
string.Format("{0:F3}", 123.456789); //123.457
string.Format("{0:F4}", 123.456789); //123.4568
Guys,
I am writing a method for rounding. Input is a decimal type (four decimal places guaranteed). The rounding rule is that 0.005 or less is ignored, i.e. look at third decimal place - if it is <= 5, round down else round up.
Some use cases : 82.3657 -> 82.36, 82.3667 -> 82.37, 82.5967 -> 82.60, 82.9958 -> 82.99, 82.9968 -> 83.00
Any good ideas? I have worked it out as follows.
private decimal CustomRound(decimal x)
{
decimal rX = Math.Truncate(x * 100) / 100;
decimal x3DecPlaces = Math.Truncate(x * 1000) / 1000;
decimal t = (x3DecPlaces * 1000) % 10;
if (t >= 6)
rX = rX + 0.01m;
return rX;
}
I don't believe there's anything built-in for that, because it's a pretty unusual requirement (for example the idea that 1.3358 is closer to 1.33 than to 1.34 is odd). Your code looks reasonably appropriate.
EDIT: You can't use MidpointRounding to get the effect you want here, because the point at which you start rounding up isn't the midpoint - it's (say) 1.336 rather than the normal 1.335. Only 1.335 is treated as the midpoint between 1.33 and 1.34, because that is the mid-point. You've effectively got a biased rounding here in an unusual way.
You can't even just truncate to three DP and then use MidpointRounding, as there's no "towards zero" mode.
One slightly odd option would be to effectively perform the bias yourself:
private static decimal CustomRound(decimal x)
{
return decimal.Round(x - 0.001m, 2, MidpointRounding.AwayFromZero);
}
So it would treat 82.3657 as 82.3647 and round that to 82.36; it would treat 82.3667 and 82.3657 and round it to 82.37, and it would treat 82.5967 as 82.5957 and round it to 82.60 etc. I think that does what you want - but only for positive values. You'd need to work out exactly what behaviour you want for negative values.
Whatever you do, you need to document it very clearly :)
Just as a matter of preference, I would use decimal.Truncate rather than Math.Truncate, just to make it clearer that everything really is done with decimals.
How do you want to handle negative values? I suppose you would want -13.999 to round to -14 not to -13.99 right?
In that case your +/- 0.01m should depend on whether x is negative or positive.
This is an easier way to do it:
decimal CustomRound(decimal x)
{
var offset = x >= 0 ? -0.001m : 0.001m;
return Decimal.Round(x + offset, 2, MidpointRounding.AwayFromZero);
}
Maybe You could use Math.Round(Double, Int32) Method?
I'm running NUnit tests to evaluate some known test data and calculated results. The numbers are floating point doubles so I don't expect them to be exactly equal, but I'm not sure how to treat them as equal for a given precision.
In NUnit we can compare with a fixed tolerance:
double expected = 0.389842845321551d;
double actual = 0.38984284532155145d; // really comes from a data import
Expect(actual, EqualTo(expected).Within(0.000000000000001));
and that works fine for numbers below zero, but as the numbers grow the tolerance really needs to be changed so we always care about the same number of digits of precision.
Specifically, this test fails:
double expected = 1.95346834136148d;
double actual = 1.9534683413614817d; // really comes from a data import
Expect(actual, EqualTo(expected).Within(0.000000000000001));
and of course larger numbers fail with tolerance..
double expected = 1632.4587642911599d;
double actual = 1632.4587642911633d; // really comes from a data import
Expect(actual, EqualTo(expected).Within(0.000000000000001));
What's the correct way to evaluate two floating point numbers are equal with a given precision? Is there a built-in way to do this in NUnit?
From msdn:
By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally.
Let's assume 15, then.
So, we could say that we want the tolerance to be to the same degree.
How many precise figures do we have after the decimal point? We need to know the distance of the most significant digit from the decimal point, right? The magnitude. We can get this with a Log10.
Then we need to divide 1 by 10 ^ precision to get a value around the precision we want.
Now, you'll need to do more test cases than I have, but this seems to work:
double expected = 1632.4587642911599d;
double actual = 1632.4587642911633d; // really comes from a data import
// Log10(100) = 2, so to get the manitude we add 1.
int magnitude = 1 + (expected == 0.0 ? -1 : Convert.ToInt32(Math.Floor(Math.Log10(expected))));
int precision = 15 - magnitude ;
double tolerance = 1.0 / Math.Pow(10, precision);
Assert.That(actual, Is.EqualTo(expected).Within(tolerance));
It's late - there could be a gotcha in here. I tested it against your three sets of test data and each passed. Changing pricision to be 16 - magnitude caused the test to fail. Setting it to 14 - magnitude obviously caused it to pass as the tolerance was greater.
This is what I came up with for The Floating-Point Guide (Java code, but should translate easily, and comes with a test suite, which you really really need):
public static boolean nearlyEqual(float a, float b, float epsilon)
{
final float absA = Math.abs(a);
final float absB = Math.abs(b);
final float diff = Math.abs(a - b);
if (a * b == 0) { // a or b or both are zero
// relative error is not meaningful here
return diff < (epsilon * epsilon);
} else { // use relative error
return diff / (absA + absB) < epsilon;
}
}
The really tricky question is what to do when one of the numbers to compare is zero. The best answer may be that such a comparison should always consider the domain meaning of the numbers being compared rather than trying to be universal.
How about converting the items each to string and comparing the strings?
string test1 = String.Format("{0:0.0##}", expected);
string test2 = String.Format("{0:0.0##}", actual);
Assert.AreEqual(test1, test2);
Assert.That(x, Is.EqualTo(y).Within(10).Percent);
is a decent option (changes it to a relative comparison, where x is required to be within 10% of y). You may want to add extra handling for 0, as otherwise you'll get an exact comparison in that case.
Update:
Another good option is
Assert.That(x, Is.EqualTo(y).Within(1).Ulps);
where Ulps means units in the last place. See https://docs.nunit.org/articles/nunit/writing-tests/constraints/EqualConstraint.html#comparing-floating-point-values.
I don't know if there's a built-in way to do it with nunit, but I would suggest multiplying each float by the 10x the precision you're seeking, storing the results as longs, and comparing the two longs to each other.
For example:
double expected = 1632.4587642911599d;
double actual = 1632.4587642911633d;
//for a precision of 4
long lActual = (long) 10000 * actual;
long lExpected = (long) 10000 * expected;
if(lActual == lExpected) { // Do comparison
// Perform desired actions
}
This is a quick idea, but how about shifting them down till they are below zero? Should be something like num/(10^ceil(log10(num))) . . . not to sure about how well it would work, but its an idea.
1632.4587642911599 / (10^ceil(log10(1632.4587642911599))) = 0.16324587642911599
How about:
const double significantFigures = 10;
Assert.AreEqual(Actual / Expected, 1.0, 1.0 / Math.Pow(10, significantFigures));
The difference between the two values should be less than either value divided by the precision.
Assert.Less(Math.Abs(firstValue - secondValue), firstValue / Math.Pow(10, precision));
open FsUnit
actual |> should (equalWithin errorMargin) expected