/Crystal 0.31

abstract struct Number

Overview

The top-level number type.

number.cr
humanize.cr
big/big_float.cr
yaml/to_yaml.cr
complex.cr

Constant Summary

SI_PREFIXES = `{ {'y', 'z', 'a', 'f', 'p', 'n', 'µ', 'm'}, {nil, 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'} }`

Default SI prefixes ordered by magnitude.

SI_PREFIXES_PADDED = ```->(magnitude : Int32, _number : Float64) do magnitude = Number.prefix_index(magnitude) {magnitude, ( magnitude == 0 ? " " : si_prefix(magnitude))} end```

SI prefixes used by `#humanize`. Equal to `SI_PREFIXES` but prepends the prefix with a space charater.

Macro Summary

• [](*nums)

Creates an `Array` of `self` with the given values, which will be casted to this type with the `new` method (defined in each `Number` type).

• slice(*nums, read_only = false)

Creates a `Slice` of `self` with the given values, which will be casted to this type with the `new` method (defined in each `Number` type).

• static_array(*nums)

Creates a `StaticArray` of `self` with the given values, which will be casted to this type with the `new` method (defined in each `Number` type).

Class Method Detail

def self.si_prefix(magnitude : Int, prefixes = SI_PREFIXES) : Char?Source

Returns the SI prefix for magnitude.

`Number.si_prefix(3) # => 'k'`

Instance Method Detail

Returns self.

def //(other)Source

Divides `self` by other using floored division.

The result will be of the same type as `self`.

def <=>(other : BigFloat)Source

Description copied from module Comparable(BigFloat)

The comparison operator. Returns `0` if the two objects are equal, a negative number if this object is considered less than other, a positive number if this object is considered greter than other, or `nil` if the two objects are not comparable.

Subclasses define this method to provide class-specific ordering.

The comparison operator is usually used to sort values:

```# Sort in a descending way:
[3, 1, 2].sort { |x, y| y <=> x } # => [3, 2, 1]

# Sort in an ascending way:
[3, 1, 2].sort { |x, y| x <=> y } # => [1, 2, 3]```

def <=>(other) : Int32?Source

The comparison operator.

Returns:

• `-1` if `self` is less than other
• `0` if `self` is equal to other
• `-1` if `self` is greater than other
• `nil` if self is `NaN` or other is `NaN`, because `NaN` values are not comparable

def absSource

Returns the absolute value of this number.

```123.abs  # => 123
-123.abs # => 123```

def abs2Source

Returns the square of `self` (`self * self`).

```4.abs2   # => 16
1.5.abs2 # => 2.25```

def clamp(range : Range)Source

Clamps a value within range.

```5.clamp(10..100)   # => 10
50.clamp(10..100)  # => 50
500.clamp(10..100) # => 100

5.clamp(10..)  # => 10
50.clamp(10..) # => 50

5.clamp(..10)  # => 5
50.clamp(..10) # => 10```

def clamp(min, max)Source

Clamps a value between min and max.

```5.clamp(10, 100)   # => 10
50.clamp(10, 100)  # => 50
500.clamp(10, 100) # => 100

5.clamp(10, nil)  # => 10
50.clamp(10, nil) # => 50

5.clamp(nil, 10)  # => 5
50.clamp(nil, 10) # => 10```

def divmod(number)Source

Returns a `Tuple` of two elements containing the quotient and modulus obtained by dividing `self` by number.

```11.divmod(3)  # => {3, 2}
11.divmod(-3) # => {-4, -1}```

def format(separator = '.', delimiter = ',', decimal_places : Int? = nil, *, group : Int = 3, only_significant : Bool = false) : StringSource

Prints this number as a `String` using a customizable format.

separator is used as decimal separator, delimiter as thousands delimiter between batches of group digits.

If decimal_places is `nil`, all significant decimal places are printed (similar to `#to_s`). If the argument has a numeric value, the number of visible decimal places will be fixed to that amount.

Trailing zeros are omitted if only_significant is `true`.

```123_456.789.format                                            # => "123,456.789"
123_456.789.format(',', '.')                                  # => "123.456,789"
123_456.789.format(decimal_places: 2)                         # => "123,456.79"
123_456.789.format(decimal_places: 6)                         # => "123,456.789000"
123_456.789.format(decimal_places: 6, only_significant: true) # => "123,456.789"```

def format(io : IO, separator = '.', delimiter = ',', decimal_places : Int? = nil, *, group : Int = 3, only_significant : Bool = false) : NilSource

Prints this number as a `String` using a customizable format.

separator is used as decimal separator, delimiter as thousands delimiter between batches of group digits.

If decimal_places is `nil`, all significant decimal places are printed (similar to `#to_s`). If the argument has a numeric value, the number of visible decimal places will be fixed to that amount.

Trailing zeros are omitted if only_significant is `true`.

```123_456.789.format                                            # => "123,456.789"
123_456.789.format(',', '.')                                  # => "123.456,789"
123_456.789.format(decimal_places: 2)                         # => "123,456.79"
123_456.789.format(decimal_places: 6)                         # => "123,456.789000"
123_456.789.format(decimal_places: 6, only_significant: true) # => "123,456.789"```

def humanize(io : IO, precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true, prefixes : Indexable = SI_PREFIXES) : NilSource

Pretty prints this number as a `String` in a human-readable format.

This is particularly useful if a number can have a wide value range and the exact value is less relevant.

It rounds the number to the nearest thousands magnitude with precision number of significant digits. The order of magnitude is expressed with an appended quantifier. By default, SI prefixes are used (see `SI_PREFIXES`).

```1_200_000_000.humanize # => "1.2G"
0.000_000_012.humanize # => "12.0n"```

If significant is `false`, the number of precision digits is preserved after the decimal separator.

```1_234.567_890.humanize(precision: 2)                     # => "1.2k"
1_234.567_890.humanize(precision: 2, significant: false) # => "1.23k"```

separator describes the decimal separator, delimiter the thousands delimiter (see `#format`).

See `Int#humanize_bytes` to format a file size.

def humanize(io : IO, precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true, prefixes : Proc) : NilSource

Pretty prints this number as a `String` in a human-readable format.

This is particularly useful if a number can have a wide value range and the exact value is less relevant.

It rounds the number to the nearest thousands magnitude with precision number of significant digits. The order of magnitude is expressed with an appended quantifier. By default, SI prefixes are used (see `SI_PREFIXES`).

```1_200_000_000.humanize # => "1.2G"
0.000_000_012.humanize # => "12.0n"```

If significant is `false`, the number of precision digits is preserved after the decimal separator.

```1_234.567_890.humanize(precision: 2)                     # => "1.2k"
1_234.567_890.humanize(precision: 2, significant: false) # => "1.23k"```

separator describes the decimal separator, delimiter the thousands delimiter (see `#format`).

This methods yields the order of magnitude and `self` and expects the block to return a `Tuple(Int32, _)` containing the (adjusted) magnitude and unit. The magnitude is typically adjusted to a multiple of `3`.

```def humanize_length(number)
number.humanize do |magnitude, number|
case magnitude
when -2, -1 then {-2, " cm"}
when .>=(4)
{3, " km"}
else
magnitude = Number.prefix_index(magnitude)
{magnitude, " #{Number.si_prefix(magnitude)}m"}
end
end
end

humanize_length(1_420) # => "1.42 km"
humanize_length(0.23)  # => "23.0 cm"```

See `Int#humanize_bytes` to format a file size.

def humanize(precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true, prefixes = SI_PREFIXES) : StringSource

Pretty prints this number as a `String` in a human-readable format.

This is particularly useful if a number can have a wide value range and the exact value is less relevant.

It rounds the number to the nearest thousands magnitude with precision number of significant digits. The order of magnitude is expressed with an appended quantifier. By default, SI prefixes are used (see `SI_PREFIXES`).

```1_200_000_000.humanize # => "1.2G"
0.000_000_012.humanize # => "12.0n"```

If significant is `false`, the number of precision digits is preserved after the decimal separator.

```1_234.567_890.humanize(precision: 2)                     # => "1.2k"
1_234.567_890.humanize(precision: 2, significant: false) # => "1.23k"```

separator describes the decimal separator, delimiter the thousands delimiter (see `#format`).

See `Int#humanize_bytes` to format a file size.

def humanize(io : IO, precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true, &prefixes : Int32, Float64 -> Tuple(Int32, UNDERSCORE) | Tuple(Int32, UNDERSCORE, Bool)) : NilSource

Pretty prints this number as a `String` in a human-readable format.

This is particularly useful if a number can have a wide value range and the exact value is less relevant.

It rounds the number to the nearest thousands magnitude with precision number of significant digits. The order of magnitude is expressed with an appended quantifier. By default, SI prefixes are used (see `SI_PREFIXES`).

```1_200_000_000.humanize # => "1.2G"
0.000_000_012.humanize # => "12.0n"```

If significant is `false`, the number of precision digits is preserved after the decimal separator.

```1_234.567_890.humanize(precision: 2)                     # => "1.2k"
1_234.567_890.humanize(precision: 2, significant: false) # => "1.23k"```

separator describes the decimal separator, delimiter the thousands delimiter (see `#format`).

This methods yields the order of magnitude and `self` and expects the block to return a `Tuple(Int32, _)` containing the (adjusted) magnitude and unit. The magnitude is typically adjusted to a multiple of `3`.

```def humanize_length(number)
number.humanize do |magnitude, number|
case magnitude
when -2, -1 then {-2, " cm"}
when .>=(4)
{3, " km"}
else
magnitude = Number.prefix_index(magnitude)
{magnitude, " #{Number.si_prefix(magnitude)}m"}
end
end
end

humanize_length(1_420) # => "1.42 km"
humanize_length(0.23)  # => "23.0 cm"```

See `Int#humanize_bytes` to format a file size.

def humanize(precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true, &block) : StringSource

Pretty prints this number as a `String` in a human-readable format.

This is particularly useful if a number can have a wide value range and the exact value is less relevant.

It rounds the number to the nearest thousands magnitude with precision number of significant digits. The order of magnitude is expressed with an appended quantifier. By default, SI prefixes are used (see `SI_PREFIXES`).

```1_200_000_000.humanize # => "1.2G"
0.000_000_012.humanize # => "12.0n"```

If significant is `false`, the number of precision digits is preserved after the decimal separator.

```1_234.567_890.humanize(precision: 2)                     # => "1.2k"
1_234.567_890.humanize(precision: 2, significant: false) # => "1.23k"```

separator describes the decimal separator, delimiter the thousands delimiter (see `#format`).

This methods yields the order of magnitude and `self` and expects the block to return a `Tuple(Int32, _)` containing the (adjusted) magnitude and unit. The magnitude is typically adjusted to a multiple of `3`.

```def humanize_length(number)
number.humanize do |magnitude, number|
case magnitude
when -2, -1 then {-2, " cm"}
when .>=(4)
{3, " km"}
else
magnitude = Number.prefix_index(magnitude)
{magnitude, " #{Number.si_prefix(magnitude)}m"}
end
end
end

humanize_length(1_420) # => "1.42 km"
humanize_length(0.23)  # => "23.0 cm"```

See `Int#humanize_bytes` to format a file size.

def humanize(precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true, prefixes : Proc) : NilSource

Pretty prints this number as a `String` in a human-readable format.

This is particularly useful if a number can have a wide value range and the exact value is less relevant.

It rounds the number to the nearest thousands magnitude with precision number of significant digits. The order of magnitude is expressed with an appended quantifier. By default, SI prefixes are used (see `SI_PREFIXES`).

```1_200_000_000.humanize # => "1.2G"
0.000_000_012.humanize # => "12.0n"```

If significant is `false`, the number of precision digits is preserved after the decimal separator.

```1_234.567_890.humanize(precision: 2)                     # => "1.2k"
1_234.567_890.humanize(precision: 2, significant: false) # => "1.23k"```

separator describes the decimal separator, delimiter the thousands delimiter (see `#format`).

This methods yields the order of magnitude and `self` and expects the block to return a `Tuple(Int32, _)` containing the (adjusted) magnitude and unit. The magnitude is typically adjusted to a multiple of `3`.

```def humanize_length(number)
number.humanize do |magnitude, number|
case magnitude
when -2, -1 then {-2, " cm"}
when .>=(4)
{3, " km"}
else
magnitude = Number.prefix_index(magnitude)
{magnitude, " #{Number.si_prefix(magnitude)}m"}
end
end
end

humanize_length(1_420) # => "1.42 km"
humanize_length(0.23)  # => "23.0 cm"```

See `Int#humanize_bytes` to format a file size.

def round(digits = 0, base = 10)Source

Rounds this number to a given precision in decimal digits.

`-1763.116.round(2) # => -1763.12`

def signSource

Returns the sign of this number as an `Int32`.

• `-1` if this number is negative
• `0` if this number is zero
• `1` if this number is positive
```123.sign # => 1
0.sign   # => 0
-42.sign # => -1```

def significant(digits, base = 10)Source

Keeps digits significants digits of this number in the given base.

```1234.567.significant(1) # => 1000
1234.567.significant(2) # => 1200
1234.567.significant(3) # => 1230
1234.567.significant(4) # => 1235
1234.567.significant(5) # => 1234.6
1234.567.significant(6) # => 1234.57
1234.567.significant(7) # => 1234.567
1234.567.significant(8) # => 1234.567

15.159.significant(1, base = 2) # => 16```

def step(*, to = nil, by = 1, &block)Source

Invokes the given block with the sequence of numbers starting at `self`, incremented by by on each call, and with an optional to.

```3.step(to: 10, by: 2) do |n|
puts n
end```

Output:

```3
5
7
9```

def zero? : BoolSource

Returns `true` if value is equal to zero.

```0.zero? # => true
5.zero? # => false```

Macro Detail

macro [](*nums)Source

Creates an `Array` of `self` with the given values, which will be casted to this type with the `new` method (defined in each `Number` type).

```floats = Float64[1, 2, 3, 4]
floats.class # => Array(Float64)

ints = Int64[1, 2, 3]
ints.class # => Array(Int64)```

macro slice(*nums, read_only = false)Source

Creates a `Slice` of `self` with the given values, which will be casted to this type with the `new` method (defined in each `Number` type).

The slice is allocated on the heap.

```floats = Float64.slice(1, 2, 3, 4)
floats.class # => Slice(Float64)

ints = Int64.slice(1, 2, 3)
ints.class # => Slice(Int64)```

macro static_array(*nums)Source

Creates a `StaticArray` of `self` with the given values, which will be casted to this type with the `new` method (defined in each `Number` type).

```floats = Float64.static_array(1, 2, 3, 4)
floats.class # => StaticArray(Float64, 4)

ints = Int64.static_array(1, 2, 3)
ints.class # => StaticArray(Int64, 3)```

© 2012–2019 Manas Technology Solutions.
Licensed under the Apache License, Version 2.0.
https://crystal-lang.org/api/0.31.1/Number.html