Sam Stone
07/04/2022, 8:34 PMGleb Minaev
07/04/2022, 9:36 PMabs(a).let { it - floor(it) }
or abs(a - truncate(a))
.
2. Well, fractional part is also a reminder of Euclidean division by `1.0`: abs(a % 1.0)
.
UPD. Sorry, I forgot case of negative a
. Fixed the bug.Sam Stone
07/05/2022, 2:45 PMGleb Minaev
07/05/2022, 3:53 PMtruncate(a * 10^n) / 10^n
.
2. Use BigDecimal
with higher precision. Then you can avoid the rounding via the precision.
3. Convert to string and truncate it manually. (But, of course, no one wants to do this. 🙂 But it's a backup plan.)Gleb Minaev
07/05/2022, 4:03 PMa - floor(a)
or a.mod(a)
.Sam Stone
07/06/2022, 2:38 PMval x = 2.123456789
println(x)
//2.123456789
Gleb Minaev
07/06/2022, 4:28 PMprintln(1_000_000_000.1 - 1_000_000_000.0) // 0.10000002384185791
// But
println(0.1) // 0.1
That's example of a collected error vs no collected error. It also means there is no way to calculate fractional part of a large number with small error using only double
.
Still, see 0.30000000000000004.com (for brief description of the problem), Wikipedia (for full description of the problem), IEEE 754 (for formal description of IEEE 754 standart that is used for double
type in a lot of modern languages).Sam Stone
07/07/2022, 8:49 PM