How to avoid NumberFormatter rounding an arbitrary-length number to infinity?

I've locally implemented some arbitrary-length number types, BigInteger and BigDecimal, which conform to NSNumber, and are based on Java's BigInteger and BigDecimal.

However I seem to be running into problems using NumberFormatter on these very large numbers.

It always rounds big values to infinity.

For example when I create a very large BigDecimal, for example,

611723274928470694720323937192057268091358137434407990501953975709196977960919583217868639381579717923158445068735090465444590083550361506503336168902106256860644729714806220531097831970159543996120528121418279220881177780748336985890481321563000228448998419698747638716248026035156519981130457085699272374625462331688.34543264678118409417047146495

... then if I make a NumberFormatter and feed this number in, it always formats it as positive infinity: +∞

Even if I set formatter.maximumIntegerDigits = 99999999, it still treats this number as +∞.

Is NumberFormatter limited in some way internally to a particular byte length of number?

I.e. is there some workaround for this problem or am I just going to have to roll my own NumberFormatter?

Thanks.

I think you are going to have to roll your own. NSNumberFormatter appears to support native integer and floating types, only.

1 Like

Also, NSNumber is not a protocol, but a Swift class in Foundation. On Darwin platforms, Swift NSNumber is interoperable with the Objective-C Foundation NSNumber. And, it is a class that only understands native integer and floating point types as noted above.

Your Formatter probably needs to be hand-rolled. Might want to inherit from the Formatter class in Foundation.

Your Formatter probably needs to be hand-rolled. Might want to inherit from the Formatter class in Foundation.

Dang. That's kinda lame.

Why doesn't Swift have arbitrary-precision types already? Kind of a pain to have to roll our own for this kind of interop with Java.

It's better to include arbitrary-precision types & formatter in swift-numerics package

Terms of Service

Privacy Policy

Cookie Policy