Last active
February 19, 2025 12:14
-
-
Save SalomonBrys/b6e344e719d82d5f6db9e9e65745405b to your computer and use it in GitHub Desktop.
Formats a double
This file contains hidden or 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
// If you are using this, please upvote this issue: https://youtrack.jetbrains.com/issue/KT-21644 | |
fun Double.toString( | |
minDecimals: Int, | |
maxDecimals: Int = minDecimals, | |
minIntegrals: Int = 1, | |
addPositiveSign: Boolean = false, | |
): String { | |
require(minDecimals <= maxDecimals) { "minDecimals > maxDecimals" } | |
require(minDecimals >= 0) { "minDecimals < 0" } | |
require(minIntegrals >= 1) { "minIntegrals < 1" } | |
val sign = if (this < 0) -1 else 1 | |
val number = this * sign | |
val (_, fullDecStr) = number.toString().split('.') | |
var int = number.toInt() | |
var decStr = fullDecStr | |
if (decStr.length > maxDecimals) { | |
decStr = fullDecStr.substring(0, maxDecimals) | |
} | |
if (fullDecStr.length > maxDecimals && fullDecStr[maxDecimals] in '5'..'9') { | |
// Need rounding | |
val digits = decStr.toCharArray() | |
var index = maxDecimals -1 | |
var needRound = true | |
while (index >= 0 && needRound) { | |
digits[index] = ((digits[index].toString().toInt() + 1) % 10).toString()[0] | |
needRound = digits[index] == '0' | |
index-- | |
} | |
if (needRound) { | |
int += 1 | |
} | |
decStr = digits.concatToString() | |
} | |
decStr = decStr.trimEnd('0') | |
return buildString { | |
when { | |
sign == -1 -> append('-') | |
sign == 1 && addPositiveSign -> append('+') | |
} | |
append(int.toString().padStart(minIntegrals, '0')) | |
if (decStr.isNotEmpty() || minDecimals >= 1) { | |
append('.') | |
append(decStr.padEnd(minDecimals, '0')) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment