How can I round to next floor 0.5 in Kotlin? - kotlin

I would like to round Double variables to the next lower 0.5 value.
For instance
12.03 -> 12
12.44 -> 12
12.56 -> 12.5
12.99 -> 12.5
There should be an elegant easy Kotlin like way?

Multiply by 2, take the floor, then divide by 2 again.
There doesn't seem to be a built-in way, but you can always write it yourself:
fun Double.roundDownToMultipleOf(base: Double): Double = base * floor(this / base)
Use as 12.56.roundDownToMultipleOf(0.5).

Related

Pandas keep decimal part of values like .998344 after round(2) applied to series

I have dataset with float values with 6 decimals. I need to round it to two decimals.The problem becams with some floats nearly close to 1. After applying round(2) I got 1.00 instead of 0.99. May be this is mathematically right, but I need to have values like 0.99. My customer needs two decimals as result, I cant change it.
ones_list = [0.998344, 0.996176, 0.998344, 0.998082]
df = pd.DataFrame(ones_list, columns=['value_to_round'])
df['value_to_round'].round(2)
1.0
1.0
1.0
1.0
I see a few options:
use floor instead of round (but would you have the same issue with 0.005?)
use clip to set a maximum (and a min?) value in the column of 0.99:
df['value_to_round'].round(2).clip(upper=0.99)
Please refer to the basic of rounding in math, you are trying to round 2 digits behind the dot using .round(2)
if you round 0.999 using .round(2), of course you'll get 1.0 because the last '9' digit (0.009) will become 0.01 thus will be added to 0.09 and become 0.1 added again with 0.9 and finally becomes 1.0
If you really want to have values like 0.99, just take the two decimals behind the dot. You can try either the following methods:
import math
df['value_to_round'] = df['value_to_round'] * 100
df['value_to_round'] = df['value_to_round'].apply(math.trunc)
df['value_to_round'] = df['value_to_round'] / 100
or
df['value_to_round'] = df['value_to_round'].astype(str)
df['value_to_round'] = df['value_to_round'].str[:4]
df['value_to_round'] = df['value_to_round'].astype(float)
I experienced the same thing when I was trying to show R squared value, what I did is just use .round(3), because 3 digits decimal wouldn't hurt
I hope this helps :)
df['value_to_round'] = [x if x < 1 else 0.99 for x in df['value_to_round'].round(2)]

kotlin - calculate Compound Interest in years

I am using Kotlin and running into a problem while calculating Compound Interest after three years.
I've tried:
fun accountInThreeYears(initial: Int, percent: Int): Double = initial + (initial * percent / 100.toDouble()) * 3
However, using an online calculator i get a different answer, what am I doing wrong?
You are missing the right formula:
value after n years = (initial value) x (1 + interest)^n
so your function should look like this:
fun accountInThreeYears(initial: Int, percent: Int): Double = initial * (1 + percent / 100.toDouble()).pow(3)
use this import for the pow() method:
import kotlin.math.pow

How would I do this in a program? Math question

I'm trying to make a generic equation which converts a value. Here are some examples.
9,873,912 -> 9,900,000
125,930 -> 126,000
2,345 -> 2,400
280 -> 300
28 -> 30
In general, x -> n
Basically, I'm making a graph and I want to make values look nicer. If it's a 6 digit number or higher, there should be at least 3 zeros. If it's a 4 digit number or less, there should be at least 2 digit numbers, except if it's a 2 digit number, 1 zero is fine.
(Ignore the commas. They are just there to help read the examples). Anyways, I want to convert a value x to this new value n. What is an equation g(x) which spits out n?
It is for an objective-c program (iPhone app).
Divide, truncate and multiply.
10**x * int(n / 10**(x-d))
What is "x"? In your examples it's about int(log10(n))-1.
What is "d"? That's the number of significant digits. 2 or 3.
Ahhh rounding is a bit awkward in programming in general. What I would suggest is dividing by the power of ten, int cast and multiplying back. Not remarkably efficient but it will work. There may be a library that can do this in Objective-C but that I do not know.
if ( x is > 99999 ) {
x = ((int)x / 1000) * 1000;
}
else if ( x > 999 ) {
x = ((int) x / 100) * 100;
}
else if ( x > 9 ) {
x = ((int) x / 10) * 10;
}
Use standard C functions like round() or roundf()... try man round at a command line, there are several different options depending on the data type. You'll probably want to scale the values first by dividing by an appropriate number and then multiplying the result by the same number, something like:
int roundedValue = round(someNumber/scalingFactor) * scalingFactor;

Rounding down with a number. Finding the n in n.mp

Bit of an odd question. I'm using cocoa.
I have a series of numbers e.g.:
0.87
0.32
1.12
2.34
8.82
12.66
and I want to get the bit before the decimal place, with no rounding.
Like this:
0.87 -> 0
0.32 -> 0
1.12 -> 1
2.34 -> 2
8.82 -> 8
12.66 -> 12
I can round the numbers with no problem, but I can't figure out how to just take the 'rounded down' figure in an elegant and non complicated way. Can you help?
use floor(double). Or cast to an int
Simply cast it to an int and you're good to go.
NSLog(#"n is %i", n);
%i will automatically cast it to int. :P
float x = 0.89;
int y = x;
int round down automatically.

Rounding a number to the nearest 5 or 10 or X

Given numbers like 499, 73433, 2348 what VBA can I use to round to the nearest 5 or 10? or an arbitrary number?
By 5:
499 -> 500
2348 -> 2350
7343 -> 7345
By 10:
499 -> 500
2348 -> 2350
7343 -> 7340
etc.
It's simple math. Given a number X and a rounding factor N, the formula would be:
round(X / N)*N
Integrated Answer
X = 1234 'number to round
N = 5 'rounding factor
round(X/N)*N 'result is 1235
For floating point to integer, 1234.564 to 1235, (this is VB specific, most other languages simply truncate) do:
int(1234.564) 'result is 1235
Beware: VB uses Bankers Rounding, to the nearest even number, which can be surprising if you're not aware of it:
msgbox round(1.5) 'result to 2
msgbox round(2.5) 'yes, result to 2 too
Thank you everyone.
To round to the nearest X (without being VBA specific)
N = X * int(N / X + 0.5)
Where int(...) returns the next lowest whole number.
If your available rounding function already rounds to the nearest whole number then omit the addition of 0.5
In VB, math.round has additional arguments to specify number of decimal places and rounding method. Math.Round(10.665, 2, MidpointRounding.AwayFromZero) will return 10.67 . If the number is a decimal or single data type, math.round returns a decimal data type. If it is double, it returns double data type. That might be important if option strict is on.
The result of (10.665).ToString("n2") rounds away from zero to give "10.67". without additional arguments math.round returns 10.66, which could lead to unwanted discrepancies.
'Example: Round 499 to nearest 5. You would use the ROUND() FUNCTION.
a = inputbox("number to be rounded")
b = inputbox("Round to nearest _______ ")
strc = Round(A/B)
strd = strc*B
msgbox( a & ", Rounded to the nearest " & b & ", is" & vbnewline & strd)
For a strict Visual Basic approach, you can convert the floating-point value to an integer to round to said integer. VB is one of the rare languages that rounds on type conversion (most others simply truncate.)
Multiples of 5 or x can be done simply by dividing before and multiplying after the round.
If you want to round and keep decimal places, Math.round(n, d) would work.
Here is our solution:
Public Enum RoundingDirection
Nearest
Up
Down
End Enum
Public Shared Function GetRoundedNumber(ByVal number As Decimal, ByVal multiplier As Decimal, ByVal direction As RoundingDirection) As Decimal
Dim nearestValue As Decimal = (CInt(number / multiplier) * multiplier)
Select Case direction
Case RoundingDirection.Nearest
Return nearestValue
Case RoundingDirection.Up
If nearestValue >= number Then
Return nearestValue
Else
Return nearestValue + multiplier
End If
Case RoundingDirection.Down
If nearestValue <= number Then
Return nearestValue
Else
Return nearestValue - multiplier
End If
End Select
End Function
Usage:
dim decTotal as Decimal = GetRoundedNumber(CDec(499), CDec(0.05), RoundingDirection.Up)
Simply ROUND(x/5)*5 should do the job.
I cannot add comment so I will use this
in a vbs run that and have fun figuring out why the 2 give a result of 2
you can't trust round
msgbox round(1.5) 'result to 2
msgbox round(2.5) 'yes, result to 2 too
something like that?
'nearest
n = 5
'n = 10
'value
v = 496
'v = 499
'v = 2348
'v = 7343
'mod
m = (v \ n) * n
'diff between mod and the val
i = v-m
if i >= (n/2) then
msgbox m+n
else
msgbox m
end if
Try this function
--------------start----------------
Function Round_Up(ByVal d As Double) As Integer
Dim result As Integer
result = Math.Round(d)
If result >= d Then
Round_Up = result
Else
Round_Up = result + 1
End If
End Function
-------------end ------------
I slightly updated the function provided by the "community wiki" (the best answer), just to round to the nearest 5 (or anything you like), with this exception : the rounded number will NEVER be superior to the original number.
This is useful in cases when it is needed to say that "a company is alive for 47 years" : I want the web page to display "is alive for more than 45 years", while avoiding lying in stating "is alive for more than 50 years".
So when you feed this function with 47, it will not return 50, but will return 45 instead.
'Rounds a number to the nearest unit, never exceeding the actual value
function RoundToNearestOrBelow(num, r)
'#param num Long/Integer/Double The number to be rounded
'#param r Long The rounding value
'#return OUT Long The rounded value
'Example usage :
' Round 47 to the nearest 5 : it will return 45
' Response.Write RoundToNearestBelow(47, 5)
Dim OUT : OUT = num
Dim rounded : rounded = Round((((num)) / r), 0) * r
if (rounded =< num) then
OUT = rounded
else
OUT = rounded - r
end if
'Return
RoundToNearestOrBelow = OUT
end function 'RoundToNearestOrBelow
To mimic in Visual Basic the way the round function works in Excel, you just have to use:
WorksheetFunction.Round(number, decimals)
This way the banking or accounting rounding don't do the rounding.