purescript/purescript-numbers

Add function(s) for converting Numbers to Strings

sharkdp opened this issue · 5 comments

As suggested by @natefaubion here. /cc @hdgarrood

It would be interesting to have a few basic functions for converting Numbers to a String.

There are several packages dealing with (pretty) printing of numbers already:

In my opinion, merging purescript-number-format into this package or implementing a similar functionality would be the best option. The API of purescript-format is probably "too opinionated" for a low-level module like this.

What do you think?

Yep, sounds sensible to me.

One suggestion I'd have is to have newtypes for the scale or radix arguments in functions like toExponential so that actually formatting the number gives you a String and not a Maybe String.

Newtypes where the constructor is not exported, that is, so that you can guarantee the value is within the range it needs to be in.

I went with a slightly different approach now, but it goes in a very similar direction to what you proposed.

https://github.com/sharkdp/purescript-numbers/blob/21cf05da5727969bb3e9ea08b45c30de68cafc14/src/Data/Number/Format.purs#L37-L62

It can be used like this:

> let x = 1234.56789

> toStringWith (precision 6) x
"1234.57"

> toStringWith (fixed 3) x
"1234.568"

> toStringWith (exponential 2) x
"1.23e+3"

Looks really nice, great work :)