Search code examples
purescript

PureScript - Convert a number to an integer?


PureScript contains a method in the Integer library fromNumber.

Here is an example of how it might be used:

myInteger = fromMaybe 0 (fromNumber myNumber)

However the docs provide this puzzling explanation:

Creates an Int from a Number value. The number must already be an integer and fall within the valid range of values for the Int type otherwise Nothing is returned.

Basically, your number must already be an Integer to convert it to an integer.

Assuming your number is not already an integer, a reasonable use case, how would you convert it to a number?


Solution

  • If it's not already an integer, there is no one true way of converting it to an integer. You could round to the nearest integer, round up, round down, do banker's rounding, or some sort of crazy conversion scheme of your own.

    The Data.Int module offers several functions for different conversion strategies, such as floor, ceil, and round.