abstract struct Number

Overview

The top-level number type.

Included Modules

Direct Known Subclasses

Defined in:

big/big_float.cr
complex.cr
humanize.cr
number.cr
uri/params/to_www_form.cr
yaml/to_yaml.cr

Constant Summary

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

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 toSI_PREFIXES but prepends the prefix with a space character.

Constructors

Class Method Summary

Macro Summary

Instance Method Summary

Instance methods inherited from module Comparable(BigFloat)

<(other : T) : Bool <, <=(other : T) <=, <=>(other : T) <=>, ==(other : T) ==, >(other : T) : Bool >, >=(other : T) >=, clamp(min, max)
clamp(range : Range)
clamp

Instance methods inherited from module Steppable

step(*, to limit = nil, by step, exclusive : Bool = false, &) : Nil
step(*, to limit = nil, by step, exclusive : Bool = false)
step

Instance methods inherited from module Comparable(Number)

<(other : T) : Bool <, <=(other : T) <=, <=>(other : T) <=>, ==(other : T) ==, >(other : T) : Bool >, >=(other : T) >=, clamp(min, max)
clamp(range : Range)
clamp

Instance methods inherited from struct Value

==(other : Log::Metadata::Value)
==(other : JSON::Any)
==(other : YAML::Any)
==(other)
==
, dup dup

Instance methods inherited from class Object

! : Bool !, !=(other) !=, !~(other) !~, ==(other) ==, ===(other : JSON::Any)
===(other : YAML::Any)
===(other)
===
, =~(other) =~, as(type : Class) as, as?(type : Class) as?, class class, dup dup, hash(hasher)
hash
hash
, in?(collection : Object) : Bool
in?(*values : Object) : Bool
in?
, inspect(io : IO) : Nil
inspect : String
inspect
, is_a?(type : Class) : Bool is_a?, itself itself, nil? : Bool nil?, not_nil!(message)
not_nil!
not_nil!
, pretty_inspect(width = 79, newline = "\n", indent = 0) : String pretty_inspect, pretty_print(pp : PrettyPrint) : Nil pretty_print, responds_to?(name : Symbol) : Bool responds_to?, tap(&) tap, to_json(io : IO) : Nil
to_json : String
to_json
, to_pretty_json(indent : String = " ") : String
to_pretty_json(io : IO, indent : String = " ") : Nil
to_pretty_json
, to_s(io : IO) : Nil
to_s : String
to_s
, to_yaml(io : IO) : Nil
to_yaml : String
to_yaml
, try(&) try, unsafe_as(type : T.class) forall T unsafe_as

Class methods inherited from class Object

from_json(string_or_io : String | IO, root : String)
from_json(string_or_io : String | IO)
from_json
, from_yaml(string_or_io : String | IO) from_yaml

Macros inherited from class Object

class_getter(*names, &block) class_getter, class_getter!(*names) class_getter!, class_getter?(*names, &block) class_getter?, class_property(*names, &block) class_property, class_property!(*names) class_property!, class_property?(*names, &block) class_property?, class_setter(*names) class_setter, def_clone def_clone, def_equals(*fields) def_equals, def_equals_and_hash(*fields) def_equals_and_hash, def_hash(*fields) def_hash, delegate(*methods, to object) delegate, forward_missing_to(delegate) forward_missing_to, getter(*names, &block) getter, getter!(*names) getter!, getter?(*names, &block) getter?, property(*names, &block) property, property!(*names) property!, property?(*names, &block) property?, setter(*names) setter

Constructor Detail

def self.additive_identity : self #

Returns the additive identity of this type.

For numerical types, it is the value0 expressed in the respective type.

Int32.additive_identity   # => 0
Float64.additive_identity # => 0.0

def self.multiplicative_identity : self #

Returns the multiplicative identity of this type.

For numerical types, it is the value1 expressed in the respective type.

Int32.multiplicative_identity   # => 1
Float64.multiplicative_identity # => 1.0

def self.zero : self #

Returns the value zero in the respective type.

Int32.zero   # => 0
Float64.zero # => 0.0

Class Method Detail

def self.si_prefix(magnitude : Int, prefixes = SI_PREFIXES) : Char | Nil #

Returns the SI prefix formagnitude.

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

Macro Detail

macro [](*nums) #

Creates anArray ofself with the given values, which will be casted to this type with thenew method (defined in eachNumber type).

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

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

This is similar to an array literal of the same item type:

Int64[1, 2, 3, 4]     # : Array(Int64)
[1, 2, 3, 4] of Int64 # : Array(Int64)

macro slice(*nums, read_only = false) #

Creates aSlice ofself with the given values, which will be casted to this type with thenew method (defined in eachNumber 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)

This is a convenient alternative toSlice.[] for designating a specific item type which also considers autocasting.

Int64.slice(1, 2, 3, 4)           # : Slice(Int64)
Slice[1_i64, 2_i64, 3_i64, 4_i64] # : Slice(Int64)

macro static_array(*nums) #

Creates aStaticArray ofself with the given values, which will be casted to this type with thenew method (defined in eachNumber 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)

This is a convenvenient alternative toStaticArray.[] for designating a specific item type which also considers autocasting.

Int64.static_array(1, 2, 3, 4)          # : StaticArray(Int64)
StaticArray[1_i64, 2_i64, 3_i64, 4_i64] # : StaticArray(Int64)

Instance Method Detail

def *(other : BigFloat) : BigFloat #

def *(other : Complex) : Complex #

def +(other : BigFloat) #

def +(other : Complex) : Complex #

def + #

Returnsself.


def -(other : BigFloat) #

def -(other : Complex) : Complex #

def /(other : BigFloat) : BigFloat #

def /(other : Complex) : Complex #

def //(other) #

Dividesself byother using floored division.

The result will be of the same type asself.


def <=>(other) : Int32 | Nil #

The comparison operator.

Returns:

  • -1 ifself is less thanother
  • 0 ifself is equal toother
  • 1 ifself is greater thanother
  • nil ifself isNaN orother isNaN, becauseNaN values are not comparable

def ==(other : Complex) #

def abs : self #

Returns the absolute value of this number.

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

def abs2 #

Returns the square ofself (self * self).

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

def cis : Complex #

Cis is a mathematical notation representingcos x + i sin x.

Returns aComplex object with real partMath.cos(self) and imaginary partMath.sin(self), whereself represents the angle in radians.


def divmod(number) #

Returns aTuple of two elements containing the quotient and modulus obtained by dividingself bynumber.

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

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

Prints this number as aString using a customizable format.

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

Ifdecimal_places isnil, 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 ifonly_significant istrue.

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(separator = '.', delimiter = ',', decimal_places : Int | Nil = nil, *, group : Int = 3, only_significant : Bool = false) : String #

Prints this number as aString using a customizable format.

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

Ifdecimal_places isnil, 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 ifonly_significant istrue.

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 hash(hasher) #

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

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

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

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

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

Ifsignificant isfalse, the number ofprecision 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).

unit_separator is inserted between the value and the unit. Users are encouraged to use a non-breaking space ('\u00A0') to prevent output being split across lines.

SeeInt#humanize_bytes to format a file size.


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

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

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

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

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

Ifsignificant isfalse, the number ofprecision 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 andself and expects the block to return aTuple(Int32, _) containing the (adjusted) magnitude and unit. The magnitude is typically adjusted to a multiple of3.

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"

SeeInt#humanize_bytes to format a file size.


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

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

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

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

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

Ifsignificant isfalse, the number ofprecision 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).

unit_separator is inserted between the value and the unit. Users are encouraged to use a non-breaking space ('\u00A0') to prevent output being split across lines.

SeeInt#humanize_bytes to format a file size.


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

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

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

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

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

Ifsignificant isfalse, the number ofprecision 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 andself and expects the block to return aTuple(Int32, _) containing the (adjusted) magnitude and unit. The magnitude is typically adjusted to a multiple of3.

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"

SeeInt#humanize_bytes to format a file size.


def humanize(precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true, unit_separator = nil, &) : String #

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

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

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

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

Ifsignificant isfalse, the number ofprecision 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 andself and expects the block to return aTuple(Int32, _) containing the (adjusted) magnitude and unit. The magnitude is typically adjusted to a multiple of3.

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"

SeeInt#humanize_bytes to format a file size.


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

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

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

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

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

Ifsignificant isfalse, the number ofprecision 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 andself and expects the block to return aTuple(Int32, _) containing the (adjusted) magnitude and unit. The magnitude is typically adjusted to a multiple of3.

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"

SeeInt#humanize_bytes to format a file size.


def i : Complex #

Returns aComplex object with the value ofself as the imaginary part.


def integer? : Bool #

Returnstrue ifself is an integer.

Non-integer types may returntrue as long asself denotes a finite value without any fractional parts.

1.integer?       # => true
1.0.integer?     # => true
1.2.integer?     # => false
(1 / 0).integer? # => false
(0 / 0).integer? # => false

def negative? : Bool #

Returnstrue ifself is less than zero.

-1.negative? # => true
0.negative?  # => false
1.negative?  # => false

def positive? : Bool #

Returnstrue ifself is greater than zero.

-1.positive? # => false
0.positive?  # => false
1.positive?  # => true

def round(mode : RoundingMode = :ties_even) : self #

Roundsself to an integer value using roundingmode.

The roundingmode controls the direction of the rounding. The default is RoundingMode::TIES_EVEN which rounds to the nearest integer, with ties (fractional value of0.5) being rounded to the even neighbor (Banker's rounding).


def round(digits : Number, base = 10, *, mode : RoundingMode = :ties_even) #

Rounds this number to a given precision.

Rounds to the specified number ofdigits after the decimal place, (or before if negative), in basebase.

The roundingmode controls the direction of the rounding. The default is RoundingMode::TIES_EVEN which rounds to the nearest integer, with ties (fractional value of0.5) being rounded to the even neighbor (Banker's rounding).

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

def sign : Int32 #

Returns the sign of this number as anInt32.

  • -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) #

Keepsdigits significant digits of this number in the givenbase.

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 limit = nil, exclusive : Bool = false, &) : Nil #

Performs a#step in the direction of thelimit. For instance:

10.step(to: 5).to_a # => [10, 9, 8, 7, 6, 5]
5.step(to: 10).to_a # => [5, 6, 7, 8, 9, 10]

def step(*, to limit = nil, exclusive : Bool = false) #

Performs a#step in the direction of thelimit. For instance:

10.step(to: 5).to_a # => [10, 9, 8, 7, 6, 5]
5.step(to: 10).to_a # => [5, 6, 7, 8, 9, 10]

def to_big_f : BigFloat #

def to_c : Complex #

Returns aComplex object with the value ofself as the real part.


def to_yaml(yaml : YAML::Nodes::Builder) : Nil #

def zero? : Bool #

Returnstrue ifself is equal to zero.

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