Scoop API

scoop:scoop.std:0.1.0

src/text/decimal_round.scoop

Selected production source · src/text/decimal_round.scoop

1package scoop.text
3internal struct RoundedDecimal(val significand: ULong, val exponent: Long, val negative: Boolean)
5private fun roundedQuotient(numerator: DecimalMagnitude, denominator: DecimalMagnitude, sticky: Boolean): ULong {
6 var shift = numerator.bitLength - denominator.bitLength
7 var quotient = 0uL
8 while (shift >= 0L) {
9 if (numerator.compareShifted(denominator, shift) >= 0L) {
10 numerator.subtractShifted(denominator, shift)
11 quotient = quotient or (1uL shl shift)
12 }
13 shift -= 1L
14 }
15 val halfway = numerator.shifted(1L).compareShifted(denominator, 0L)
16 if (halfway > 0L || (halfway == 0L && (sticky || (quotient and 1uL) != 0uL))) quotient += 1uL
17 return quotient
20internal fun roundDecimal(text: String, precision: Long, minExponent: Long, minOrder: Long, maxOrder: Long): RoundedDecimal? {
21 val parsed = when (scanDecimal(text, precision + 2L - minExponent)) {
22 case None -> return None
23 case Some(val value) -> value
24 }
25 if (parsed.digits == 0L || parsed.order < minOrder) return Some(RoundedDecimal(0uL, 0L, parsed.negative))
26 if (parsed.order > maxOrder) return None
27 var numerator = parsed.magnitude
28 var denominator = DecimalMagnitude()
29 denominator.multiplyAdd(10u, 1u)
30 var decimalExponent = parsed.order - parsed.digits + 1L
31 while (decimalExponent > 0L) { numerator.multiplyAdd(10u, 0u); decimalExponent -= 1L }
32 while (decimalExponent < 0L) { denominator.multiplyAdd(10u, 0u); decimalExponent += 1L }
33 var binaryOrder = numerator.bitLength - denominator.bitLength
34 val comparison = if (binaryOrder >= 0L) numerator.compareShifted(denominator, binaryOrder)
35 else numerator.shifted(-binaryOrder).compareShifted(denominator, 0L)
36 if (comparison < 0L) binaryOrder -= 1L
37 val normalExponent = binaryOrder - precision + 1L
38 val exponent = if (normalExponent < minExponent) minExponent else normalExponent
39 if (exponent < 0L) numerator = numerator.shifted(-exponent)
40 else denominator = denominator.shifted(exponent)
41 return Some(RoundedDecimal(roundedQuotient(numerator, denominator, parsed.sticky), exponent, parsed.negative))