in Excel, =ROUNDUP(474.872126666666, 2) -> 474.88
in .NET,
Math.Round(474.87212666666666666666666666667, 2, MidpointRounding.ToEven) // 474.87
Math.Round(474.87212666666666666666666666667, 2, MidpointRounding.AwayFromZero) // 474.87
My client want Excel rounding result, is there any way I can get 474.88 in .NET?
Thanks a lot
double ROUNDUP( double number, int digits )
{
return Math.Ceiling(number * Math.Pow(10, digits)) / Math.Pow(10, digits);
}
Math.Ceiling is what you're looking for.
Here's my try on a solution that behaves like Excel ROUNDUP function.
I tried to cover cases such as: negative decimal numbers, negative digits (yep Excel supports that), large decimal values
public static decimal RoundUp(decimal number, int digits)
{
if (digits > 0)
{
// numbers will have a format like +/-1.23, where the fractional part is optional if numbers are integral
// Excel RoundUp rounds negative numbers as if they were positive.
// To simulate this behavior we will use the absolute value of the number
// E.g. |1.23| = |-1.23| = 1.23
var absNumber = Math.Abs(number);
// Now take the integral part (E.g. for 1.23 is 1)
var absNumberIntegralPart = Decimal.Floor(absNumber);
// Now take the fractional part (E.g. for 1.23 is 0.23)
var fraction = (absNumber - absNumberIntegralPart);
// Multiply fractional part by the 10 ^ number of digits we're rounding to
// E.g. For 1.23 with rounded to 1 digit it will be 0.23 * 10^1 = 2.3
// Then we round that value UP using Decimal.Ceiling and we transform it back to a fractional part by dividing it by 10^number of digits
// E.g. Decimal.Ceiling(0.23 * 10) / 10 = Decimal.Ceiling(2.3) / 10 = 3 / 10 = 0.3
var tenPower = (decimal)Math.Pow(10, digits);
var fractionRoundedUp = Decimal.Ceiling(fraction * tenPower) / tenPower;
// Now we add up the absolute part with the rounded up fractional part and we put back the negative sign if needed
// E.g. 1 + 0.3 = 1.3
return Math.Sign(number) * (absNumberIntegralPart + fractionRoundedUp);
} else if (digits == 0)
{
return Math.Sign(number) * Decimal.Ceiling(Math.Abs(number));
} else if (digits < 0)
{
// negative digit rounding means that for RoundUp(149.12, -2) we will discard the fractional part, shift the decimal point on the left part 2 places before rounding up
// then replace all digits on the right of the decimal point with zeroes
// E.g. RoundUp(149.12, -2). Shift decimal point 2 places => 1.49. Now roundup(1.49) = 2 and we put 00 instead of 49 => 200
var absNumber = Math.Abs(number);
var absNumberIntegralPart = Decimal.Floor(absNumber);
var tenPower = (decimal)Math.Pow(10, -digits);
var absNumberIntegraPartRoundedUp = Decimal.Ceiling(absNumberIntegralPart / tenPower) * tenPower;
return Math.Sign(number)*absNumberIntegraPartRoundedUp;
}
return number;
}
[TestMethod]
public void Can_RoundUp_Correctly()
{
Assert.AreEqual(1.466m, MathExtensions.RoundUp(1.4655m, 3));
Assert.AreEqual(-1.466m, MathExtensions.RoundUp(-1.4655m, 3));
Assert.AreEqual(150m, MathExtensions.RoundUp(149.001m, 0));
Assert.AreEqual(-150m, MathExtensions.RoundUp(-149.001m, 0));
Assert.AreEqual(149.2m, MathExtensions.RoundUp(149.12m, 1));
Assert.AreEqual(149.12m, MathExtensions.RoundUp(149.12m, 2));
Assert.AreEqual(1232m, MathExtensions.RoundUp(1232, 2));
Assert.AreEqual(200m, MathExtensions.RoundUp(149.123m, -2));
Assert.AreEqual(-200m, MathExtensions.RoundUp(-149.123m, -2));
Assert.AreEqual(-20m, MathExtensions.RoundUp(-12.4655m, -1));
Assert.AreEqual(1.67m, MathExtensions.RoundUp(1.666666666666666666666666666m, 2));
Assert.AreEqual(1000000000000000000000000000m, MathExtensions.RoundUp(999999999999999999999999999m, -2));
Assert.AreEqual(10000000000000m, MathExtensions.RoundUp(9999999999999.999m, 2));
}
Here is the correct calculation for ROUNDUP and ROUNDDOWN:
private static object RoundDown(List<Expression> p)
{
var target = (decimal)p[0].Evaluate();
var digits = (decimal)p[1].Evaluate();
if (target < 0) return (Math.Ceiling((double)target * Math.Pow(10, (int)digits)) / Math.Pow(10, (int)digits));
return Math.Floor((double)target * Math.Pow(10, (int)digits)) / Math.Pow(10, (int)digits);
}
private static object RoundUp(List<Expression> p)
{
var target = (decimal)p[0].Evaluate();
var digits = (decimal)p[1].Evaluate();
if (target < 0) return (Math.Floor((double)target * Math.Pow(10, (int)digits)) / Math.Pow(10, (int)digits));
return Math.Ceiling((double)target * Math.Pow(10, (int)digits)) / Math.Pow(10, (int)digits);
}
Related
This question already has answers here:
C# is rounding down divisions by itself
(10 answers)
Closed 4 years ago.
I am performing calculations on 2 numbers like below :
No1 = 263
No2 = 260
Decimal places = 2
Expected output = 98.86
Code :
decimal output = 0;
int decimalPlaces = 2;
if (No1 > 0)
output = ((100 * Convert.ToDecimal(((No2 * 100) / No1))) / 100);
output = TruncateDecimal(output, decimalPlaces); // 98
public static decimal TruncateDecimal(decimal value, int precision)
{
decimal step = (decimal)Math.Pow(10, precision);
decimal tmp = Math.Truncate(step * value);
return tmp / step;
}
Above code renders output = 98
When i divide 263/260 in calculator i get 0.988593
decimalPlaces = 2 : Take 2 digits after decimal places
decimalPlaces = 2 : Round off will also take from this position after 2 decimal places i.e round off should take from 593 rendering 98.86
No1 = 117
No2 = 120
decimal places = 2
Expected Output = 97.50
Can anybody please me with this?
The problem is integer division. When you divide an integer by an integer, you will get an integer. You need to cast the values (at minimum one of them) to a decimal
output = Math.Round((100 * ((decimal)No2/(decimal)No1)),2);
try to change some parenthesis positions, from:
output = ((100 * Convert.ToDecimal(((No2 * 100) / No1))) / 100);
to
output = ((100 * ((Convert.ToDecimal(No2 * 100) / No1))) / 100);
In your code the division is calculated before decimal conversion, so you convert only integer result of the division.
Besides use Math.Round instead of Math.Truncate, in order to get your desired result.
I need to convert a double value (centimeters) to a fraction value with this format: 3 1/64 (inches). After reading a lot about this and finding algorithms for converting into fractions, I think they are not good for what I need, because my fractions should be in these formats: ?/2, ?/4, ?/8, ?/16, ?/32, ?/64. I have seen conversion tables like this: table. And I think my best solution is to create a key, value list with all values in the table and for each number find the best approximation in the list.
For example: 3.21 cm. = 1.26378 in = 1 in + 0.26378. So, according the table linked, 0.26378 = 17/64. And the final result should be 1 17/64 inches.
So my questions are:
Is a good idea to have a list with the values in the table and find the closest value in order to give the fraction or it is better to create an algorithm for this?
In case it is fine to create a list with the values, how can I find the closest value of a given number in my list?
I suggest using simple math instead of table
private static string ToFraction64(double value) {
// denominator is fixed
int denominator = 64;
// integer part, can be signed: 1, 0, -3,...
int integer = (int) value;
// numerator: always unsigned (the sign belongs to the integer part)
// + 0.5 - rounding, nearest one: 37.9 / 64 -> 38 / 64; 38.01 / 64 -> 38 / 64
int numerator = (int) ((Math.Abs(value) - Math.Abs(integer)) * denominator + 0.5);
// some fractions, e.g. 24 / 64 can be simplified:
// both numerator and denominator can be divided by the same number
// since 64 = 2 ** 6 we can try 2 powers only
// 24/64 -> 12/32 -> 6/16 -> 3/8
// In general case (arbitrary denominator) use gcd (Greatest Common Divisor):
// double factor = gcd(denominator, numerator);
// denominator /= factor;
// numerator /= factor;
while ((numerator % 2 == 0) && (denominator % 2 == 0)) {
numerator /= 2;
denominator /= 2;
}
// The longest part is formatting out
// if we have an actual, not degenerated fraction (not, say, 4 0/1)
if (denominator > 1)
if (integer != 0) // all three: integer + numerator + denominator
return string.Format("{0} {1}/{2}", integer, numerator, denominator);
else if (value < 0) // negative numerator/denominator, e.g. -1/4
return string.Format("-{0}/{1}", numerator, denominator);
else // positive numerator/denominator, e.g. 3/8
return string.Format("{0}/{1}", numerator, denominator);
else
return integer.ToString(); // just an integer value, e.g. 0, -3, 12...
}
Tests
const double cmInInch = 2.54;
// 1 17/64
Console.Write(ToFraction64(3.21 / cmInInch));
// -1 17/64
Console.Write(ToFraction64(-1.26378));
// 3 1/4
Console.Write(ToFraction64(3.25001));
// 3 1/4
Console.Write(ToFraction64(3.24997));
// 5
Console.Write(ToFraction64(5.000001));
// -1/8
Console.Write(ToFraction64(-0.129));
// 1/8
Console.Write(ToFraction64(0.129));
Added display of feet
public static string ToFraction(this double source, int denominator)
{
var divider = denominator;
var inches = (int) Math.Abs(source);
var numerator = (int) ((Math.Abs(source) - Math.Abs(inches)) * divider + 0.5);
while (numerator % 2 == 0 && divider % 2 == 0)
{
numerator /= 2;
divider /= 2;
}
if (divider == numerator)
{
if (source < 0) inches--;
else inches++;
numerator = 0;
}
var feet = Math.DivRem(inches, 12, out inches);
var valueBuilder = new StringBuilder();
if (source + 1d / denominator < 0) valueBuilder.Insert(0, "-");
if (feet > 0)
{
valueBuilder.Append(feet);
valueBuilder.Append("'");
valueBuilder.Append("-");
}
valueBuilder.Append(inches);
if (numerator != 0)
{
valueBuilder.Append(" ");
valueBuilder.Append(numerator);
valueBuilder.Append("/");
valueBuilder.Append(divider);
}
valueBuilder.Append('"');
return valueBuilder.ToString();
}
All tests passed
[TestCase]
public void FractionTest()
{
Assert.AreEqual("0\"", 0d.ToFraction());
Assert.AreEqual("0\"", (-0d).ToFraction());
Assert.AreEqual("0\"", (-0.00001d).ToFraction());
Assert.AreEqual("1\"", 1d.ToFraction());
Assert.AreEqual("-1\"", (-1d).ToFraction());
Assert.AreEqual("0 1/8\"", 0.129.ToFraction());
Assert.AreEqual("-0 1/8\"", (-0.129).ToFraction());
Assert.AreEqual("-1 1/4\"", (-1.26378).ToFraction());
Assert.AreEqual("5\"", 5.000001.ToFraction());
Assert.AreEqual("3 1/4\"", 3.24997.ToFraction());
Assert.AreEqual("3 1/4\"", 3.25001.ToFraction());
Assert.AreEqual("1'-0\"", 12d.ToFraction());
Assert.AreEqual("1'-0 3/32\"", 12.1d.ToFraction());
Assert.AreEqual("1'-1\"", 13d.ToFraction());
Assert.AreEqual("1'-3 1/8\"", 15.125d.ToFraction());
Assert.AreEqual("1'-0\"", 12.00001d.ToFraction());
Assert.AreEqual("-1'-0\"", (-12.00001d).ToFraction());
Assert.AreEqual("-2'-1 7/32\"", (-25.231d).ToFraction());
}
taking the code of Dmitry Bychenko, we need to add the case "else if (denominator == numerator)" if fraction equals to 1 to add 1 if the value is positive or remove 1 if the value is negative (ex denominator/numerator = 64/64)
private static string ToFraction64(double value)
{
// denominator is fixed
int denominator = 64;
// integer part, can be signed: 1, 0, -3,...
int integer = (int)value;
// numerator: always unsigned (the sign belongs to the integer part)
// + 0.5 - rounding, nearest one: 37.9 / 64 -> 38 / 64; 38.01 / 64 -> 38 / 64
int numerator = (int)((Math.Abs(value) - Math.Abs(integer)) * denominator + 0.5);
// some fractions, e.g. 24 / 64 can be simplified:
// both numerator and denominator can be divided by the same number
// since 64 = 2 ** 6 we can try 2 powers only
// 24/64 -> 12/32 -> 6/16 -> 3/8
// In general case (arbitrary denominator) use gcd (Greatest Common Divisor):
// double factor = gcd(denominator, numerator);
// denominator /= factor;
// numerator /= factor;
while ((numerator % 2 == 0) && (denominator % 2 == 0))
{
numerator /= 2;
denominator /= 2;
}
// The longest part is formatting out
// if we have an actual, not degenerated fraction (not, say, 4 0/1)
if (denominator > 1)
if (integer != 0) // all three: integer + numerator + denominator
return string.Format("{0} {1}/{2}", integer, numerator, denominator);
else if (value < 0) // negative numerator/denominator, e.g. -1/4
return string.Format("-{0}/{1}", numerator, denominator);
else // positive numerator/denominator, e.g. 3/8
return string.Format("{0}/{1}", numerator, denominator);
//if fraction equals to 1 we add 1 if the value is positive or remove 1 if the value is negative (ex denominator/numerator = 64/64)
else if (denominator == numerator)
{
if (value < 0) // negative numerator/denominator, e.g. -1/4
integer--;
else // positive numerator/denominator, e.g. 3/8
integer++;
return integer.ToString();
}
else
return integer.ToString(); // just an integer value, e.g. 0, -3, 12...
}
My function is easier and more simple..
It return an array of three integer {Inches, Numerator, Denominator} from a decimal value, the fracBase argument mean the precision as 16, 32, 64, 128 ....
public static int[] GetImpFractions(decimal value, int fracBase = 32)
{
int[] result = { 0, 0, 0 };
result[0] = (int)Math.Truncate(value);
decimal num = (value - (decimal)result[0]);
num *= fracBase;
decimal denom = fracBase;
if (num > 0)
{
while (num % 2 == 0)
{
num /= 2;
denom /= 2;
}
if (num == 1 && denom == 1)
{
result[0] += 1;
num = 0;
denom = 0;
}
result[1] = (int)Math.Truncate(num);
result[2] = (int)Math.Truncate(denom);
}
return result;
}
I want to round this decimal number 14999994 to this value 15000000, but Math.Round() doesn't work for me!
Please notice that my decimal number doesn't have any precision
static double RoundToSignificantDigits(double d, int digits)
{
if (d == 0)
{
return 0;
}
double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1 - digits);
return Math.Sign(d) * scale * Math.Ceiling(Math.Abs(d) / scale);
}
It's based on calculating a "scale" based on the Math.Log10 (but note that Math.Abs for the negative numbers!), minus the digits precision given, then dividing the number by this "scale", rounding and re-multiplying by this "scale". Note even the use of Math.Sign: we round up (Math.Ceiling) the absolute value of d and then "reattach" the sign.
Use it like:
double n = RoundToSignificantDigits(14999994, 2); // 15000000
Note that double are an ugly beast:
double num = 0.2;
num += 0.1; // 0.30000000000000004
double num2 = RoundToSignificantDigits(num, 1); // 0.4
I need to truncate a number to 2 decimal places, which basically means
chopping off the extra digits.
Eg:
2.919 -> 2.91
2.91111 -> 2.91
Why? This is what SQL server is doing when storing a number of a
particular precision. Eg, if a column is Decimal(8,2), and you try to
insert/update a number of 9.1234, the 3 and 4 will be chopped off.
I need to do exactly the same thing in c# code.
The only possible ways that I can think of doing it are either:
Using the stringformatter to "print" it out only
two decimal places, and then converting it to a decimal,
eg:
decimal tooManyDigits = 2.1345
decimal ShorterDigits = Convert.ToDecimal(tooManyDigits.ToString("0.##"));
// ShorterDigits is now 2.13
I'm not happy with this because it involves a to-string and then
another string to decimal conversion which seems a bit mad.
Using Math.Truncate (which only accepts an integer), so I
can multiply it by 100, truncate it, then divide by 100. eg:
decimal tooLongDecimal = 2.1235;
tooLongDecimal = Math.Truncate(tooLongDecimal * 100) / 100;
I'm also not happy with this because if tooLongDecimal is 0,
I'll get a divide by 0 error.
Surely there's a better + easier way! Any suggestions?
You've answered the question yourself; it seems you just misunderstood what division by zero means. The correct way to do this is to multiply, truncate, then devide, like this:
decimal TruncateTo100ths(decimal d)
{
return Math.Truncate(d* 100) / 100;
}
TruncateTo100ths(0m); // 0
TruncateTo100ths(2.919m); // 2.91
TruncateTo100ths(2.91111m); // 2.91
TruncateTo100ths(2.1345m); // 2.13
There is no division by zero here, there is only division by 100, which is perfectly safe.
The previously offered mathematical solutions are vulnerable to overflow with large numbers and/or a large number of decimal places. Consider instead the following extension method:
public static decimal TruncateDecimal(this decimal d, int decimals)
{
if (decimals < 0)
throw new ArgumentOutOfRangeException("decimals", "Value must be in range 0-28.");
else if (decimals > 28)
throw new ArgumentOutOfRangeException("decimals", "Value must be in range 0-28.");
else if (decimals == 0)
return Math.Truncate(d);
else
{
decimal integerPart = Math.Truncate(d);
decimal scalingFactor = d - integerPart;
decimal multiplier = (decimal) Math.Pow(10, decimals);
scalingFactor = Math.Truncate(scalingFactor * multiplier) / multiplier;
return integerPart + scalingFactor;
}
}
Usage:
decimal value = 18446744073709551615.262626263m;
value = value.TruncateDecimal(6); // Result: 18446744073709551615.262626
I agree with p.s.w.g. I had the similar requirement and here is my experience and a more generalized function for truncating.
http://snathani.blogspot.com/2014/05/truncating-number-to-specificnumber-of.html
public static decimal Truncate(decimal value, int decimals)
{
decimal factor = (decimal)Math.Pow(10, decimals);
decimal result = Math.Truncate(factor * value) / factor;
return result;
}
Using decimal.ToString('0.##') also imposes rounding:
1.119M.ToString("0.##") // -> 1.12
(Yeah, likely should be a comment, but it's hard to format well as such.)
public static decimal Rounding(decimal val, int precision)
{
decimal res = Trancating(val, precision + 1);
return Math.Round(res, precision, MidpointRounding.AwayFromZero);
}
public static decimal Trancating(decimal val,int precision)
{
if (val.ToString().Contains("."))
{
string valstr = val.ToString();
string[] valArr = valstr.Split('.');
if(valArr[1].Length < precision)
{
int NoOfZeroNeedToAdd = precision - valArr[1].Length;
for (int i = 1; i <= NoOfZeroNeedToAdd; i++)
{
valstr = string.Concat(valstr, "0");
}
}
if(valArr[1].Length > precision)
{
valstr = valArr[0] +"."+ valArr[1].Substring(0, precision);
}
return Convert.ToDecimal(valstr);
}
else
{
string valstr=val.ToString();
for(int i = 0; i <= precision; i++)
{
if (i == 1)
valstr = string.Concat(valstr, ".0");
if(i>1)
valstr = string.Concat(valstr, "0");
}
return Convert.ToDecimal(valstr);
}
}
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!