Skip to content

Commit 3020aac

Browse files
committed
Fix (Double/Float).toPrecision() exceptions
1 parent f02729b commit 3020aac

File tree

2 files changed

+19
-12
lines changed

2 files changed

+19
-12
lines changed

.idea/misc.xml

Lines changed: 0 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

needtool/src/main/java/ir/am3n/needtool/NumberHelper.kt

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -284,18 +284,26 @@ fun Double?.ifNullOrZero(defaultValue: String): String {
284284
}
285285

286286
fun Float.toPrecision(precision: Int) =
287-
this.toDouble().toPrecision(precision)
287+
try {
288+
this.toDouble().toPrecision(precision)
289+
} catch (t: Throwable) {
290+
this.toString()
291+
}
288292

289293
fun Double.toPrecision(precision: Int) =
290-
if (precision < 1) {
291-
"${this.roundToInt()}"
292-
} else {
293-
val p = 10.0.pow(precision)
294-
val v = (abs(this) * p).roundToInt()
295-
val i = floor(v / p)
296-
var f = "${floor(v - (i * p)).toInt()}"
297-
while (f.length < precision) f = "0$f"
298-
val s = if (this < 0) "-" else ""
299-
"$s${i.toInt()}.$f"
294+
try {
295+
if (precision < 1) {
296+
"${this.roundToInt()}"
297+
} else {
298+
val p = 10.0.pow(precision)
299+
val v = (abs(this) * p).roundToInt()
300+
val i = floor(v / p)
301+
var f = "${floor(v - (i * p)).toInt()}"
302+
while (f.length < precision) f = "0$f"
303+
val s = if (this < 0) "-" else ""
304+
"$s${i.toInt()}.$f"
305+
}
306+
} catch (t: Throwable) {
307+
this.toString()
300308
}
301309

0 commit comments

Comments
 (0)