I looked but was unable to find anything similar to Python's sigfig library. Does something like this exist for Nim?
I want to be able to express a number with a given amount of significant digits. Ideally I'd have the option to show this in scientific or engineering notation too.
I tried getting Grok AI to give me a start, but it kept trying to do nested curly braces in the fmt call.
thanks
If you only need a string value for output, use strutils.formatfloat():
import std/strutils
echo formatFloat(123.129, ffDecimal, 2) # 123.13
echo formatFloat(123.129, ffScientific, 2) # 1.23e+02
If you need actual fp number rounded by decimals - I don't see the point, but here is how you can do this:
import std/math
proc truncToDecimal[T: SomeFloat](n: T, places: Natural): T =
let t = T(10 ^ places)
trunc(n * t) / t
proc roundToDecimal[T: SomeFloat](n: T, places: Natural): T =
let t = T(10 ^ places)
round(n * t) / t
echo roundToDecimal(123.1299999, 2) # 123.13
echo truncToDecimal(123.1299999, 0) # 123.0
echo truncToDecimal(123.1299999, 1) # 123.1
echo truncToDecimal(123.1299999, 2) # 123.12
echo truncToDecimal(123.1299999, 3) # 123.129