Last active
July 2, 2019 05:58
-
-
Save rodrigosimoesrosa/fa7f8b12ecf9d1f2a7b390ad2fafb1aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.math.RoundingMode | |
import kotlin.math.round | |
/** | |
* Created by rodrigosimoesrosa. | |
*/ | |
const val DIGITS = 1 | |
fun Float.round(decimals: Int = DIGITS): Float { | |
var multiplier = 1.0f | |
repeat(decimals) { multiplier *= 10 } | |
return round(this * multiplier) / multiplier | |
} | |
fun Float.roundCeiling(digits: Int = DIGITS): Float { | |
return toBigDecimal().setScale(digits, RoundingMode.CEILING).toFloat() | |
} | |
fun Float.roundFloor(digits: Int = DIGITS): Float { | |
return toBigDecimal().setScale(digits, RoundingMode.FLOOR).toFloat() | |
} | |
fun Float.roundHalfEven(digits: Int = DIGITS): Float { | |
return toBigDecimal().setScale(digits, RoundingMode.HALF_EVEN).toFloat() | |
} | |
fun Float.roundHalfDown(digits: Int = DIGITS): Float { | |
return toBigDecimal().setScale(digits, RoundingMode.HALF_DOWN).toFloat() | |
} | |
infix fun ClosedRange<Float>.step(step: Float): Iterable<Float> { | |
require(start.isFinite()) | |
require(endInclusive.isFinite()) | |
require(step.round() > 0.0) { "Step must be positive, was: $step." } | |
require(start != endInclusive) { "start and endInclusive must not be the same" } | |
if (endInclusive > start) { | |
return generateSequence(start) { previous -> | |
if (previous == Float.POSITIVE_INFINITY) return@generateSequence null | |
val next = previous + step.round() | |
if (next > endInclusive) null else next.round() | |
}.asIterable() | |
} | |
return generateSequence(start) { previous -> | |
if (previous == Float.NEGATIVE_INFINITY) return@generateSequence null | |
val next = previous - step.round() | |
if (next < endInclusive) null else next.round() | |
}.asIterable() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(1.0f .. 0.0f).step(.1f).forEach { System.out.println("value: $it") }
output:
value: 1.0
value: 0.9
value: 0.8
value: 0.7
value: 0.6
value: 0.5
value: 0.4
value: 0.3
value: 0.2
value: 0.1
value: 0.0
(0.0f .. 1.0f).step(.1f).forEach { System.out.println("value: $it") }
output:
value: 0.0
value: 0.1
value: 0.2
value: 0.3
value: 0.4
value: 0.5
value: 0.6
value: 0.7
value: 0.8
value: 0.9
value: 1.0