Skip to content

Commit

Permalink
Add fromNumber
Browse files Browse the repository at this point in the history
  • Loading branch information
sharkdp committed Jan 16, 2018
1 parent 4118222 commit d9eebc1
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
8 changes: 8 additions & 0 deletions docs/Data/BigInt.md
Expand Up @@ -29,6 +29,14 @@ fromInt :: Int -> BigInt

Convert an integer to a BigInt.

#### `fromNumber`

``` purescript
fromNumber :: Number -> BigInt
```

Convert a Number to a BigInt. The fractional part is truncated.

#### `toNumber`

``` purescript
Expand Down
9 changes: 9 additions & 0 deletions src/Data/BigInt.js
Expand Up @@ -19,6 +19,15 @@ exports["fromBase'"] = function(just) {

exports.fromInt = bigInt;

function truncate(n) {
if (n > 0) return Math.floor(n);
return Math.ceil(n);
}

exports.fromNumber = function(x) {
return bigInt(truncate(x));
};

exports.toBase = function(base) {
return function (x) {
return x.toString(base);
Expand Down
4 changes: 4 additions & 0 deletions src/Data/BigInt.purs
Expand Up @@ -4,6 +4,7 @@ module Data.BigInt
, fromString
, fromBase
, fromInt
, fromNumber
, toString
, toBase
, abs
Expand Down Expand Up @@ -38,6 +39,9 @@ foreign import fromBase' :: forall a. (a -> Maybe a)
-- | Convert an integer to a BigInt.
foreign import fromInt :: Int -> BigInt

-- | Convert a Number to a BigInt. The fractional part is truncated.
foreign import fromNumber :: Number -> BigInt

-- | Converts a BigInt to a Number. Loses precision for numbers which are too
-- | large.
foreign import toNumber :: BigInt -> Number
Expand Down
11 changes: 10 additions & 1 deletion test/Main.purs
Expand Up @@ -5,7 +5,8 @@ import Control.Monad.Eff.Console (CONSOLE, log)
import Control.Monad.Eff.Exception (EXCEPTION)
import Control.Monad.Eff.Random (RANDOM)
import Data.Array (filter, range)
import Data.BigInt (BigInt, abs, fromInt, prime, pow, odd, even, fromString, toNumber, fromBase, toBase, toString, not, or, xor, and, shl, shr)
import Data.BigInt (BigInt, abs, fromInt, fromNumber, prime, pow, odd, even, fromString, toNumber,
fromBase, toBase, toString, not, or, xor, and, shl, shr)
import Data.Foldable (fold)
import Data.Int as Int
import Data.Maybe (Maybe(..), fromMaybe)
Expand Down Expand Up @@ -85,6 +86,14 @@ main = do
assert $ (toBase 16 <$> fromString "255") == Just "ff"
assert $ toString (fromInt 12345) == "12345"

log "Converting from Number to BigInt"
assert $ fromNumber 0.0 == zero
assert $ fromNumber 3.4 == three
assert $ fromNumber (-3.9) == -three
assert $ fromNumber 1.0e7 == fromInt 10000000
assert $ Just (fromNumber 1.0e47) == fromString "1e47"
quickCheck (\x -> fromInt x == fromNumber (Int.toNumber x))

log "Conversions between String, Int and BigInt should not loose precision"
quickCheck (\n -> fromString (show n) == Just (fromInt n))
quickCheck (\n -> Int.toNumber n == toNumber (fromInt n))
Expand Down

0 comments on commit d9eebc1

Please sign in to comment.