Перейти к содержимому
Топаз6.0 · До релиза
Загрузка →

Поиск в документации

Спецификация 6.0

Выберите результат стрелками и нажмите Enter, чтобы открыть его.

Введите имя API, номер диагностики, правило или тему проекта.

    Библиотека · std.decimal

    Decimal.toInt

    Convert an exact integral Decimal within the signed int range.

    toInt() -> Option<int>
    Модуль
    std.decimal →
    Получатель
    Decimal
    Минимальное число аргументов
    0
    Максимальное число аргументов
    0

    Declaration and parameters

    Ссылка

    Доступность

    Включено по умолчанию · Не определено

    Import std.decimal in language mode 5.21.

    The current compiler selects std/decimal.tpz for this language mode. Availability in other released editions and inclusion in each installed distribution are Pending.

    Получатель

    Decimal

    Ограничения параметров

    int.toDecimal converts every int value exactly and produces scale zero. Both signed 64 bit endpoints are representable. The conversion does not pass through float.

    Decimal.toInt returns Some containing the same integer when the Decimal is integral and fits the integer conversion bounds.

    A nonintegral Decimal or an integer outside the int range returns None(). Conversion does not round, truncate, wrap, saturate, or raise an arithmetic overflow fault. The original Decimal remains unchanged.

    A value parsed from 1.000 is integral after normalization and converts to Some containing 1. A value parsed from 1.001 is nonintegral and returns None().

    Existing int, float and BigInt values do not implicitly become Decimal values in arithmetic or comparisons. The module provides no direct float or BigInt conversion member.

    For an exact BigInt conversion, format it with radix 10 and pass that text to Decimal.parse. To request an integral BigInt from a Decimal, pass its canonical text to BigInt.parse with radix 10. Fractional decimal text is rejected by that integer parser.

    Converting through explicitly chosen text follows the corresponding text parser. Decimal.parse never recovers decimal digits that were lost in an earlier binary float calculation.

    Результат

    The declared result type is Option<int>.

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Return Some for an integral value from -9223372036854775808 through 9223372036854775807. Return None() for a fraction or a value outside that range without changing the receiver.

    Checked narrowing preserves the value instead of choosing a rounding or overflow policy implicitly.

    Resolved contracts

    Ссылка

    Related entries

    Ссылка

    std.decimal →

    Convert numeric values explicitly and without truncation

    Ссылка
    Правилоtopaz.stdlib.contract.decimal-conversion.rule

    Convert numeric values explicitly and without truncation

    int.toDecimal converts every int value exactly and produces scale zero. Both signed 64 bit endpoints are representable. The conversion does not pass through float.

    Decimal.toInt returns Some containing the same integer when the Decimal is integral and fits the integer conversion bounds.

    A nonintegral Decimal or an integer outside the int range returns None(). Conversion does not round, truncate, wrap, saturate, or raise an arithmetic overflow fault. The original Decimal remains unchanged.

    A value parsed from 1.000 is integral after normalization and converts to Some containing 1. A value parsed from 1.001 is nonintegral and returns None().

    Existing int, float and BigInt values do not implicitly become Decimal values in arithmetic or comparisons. The module provides no direct float or BigInt conversion member.

    For an exact BigInt conversion, format it with radix 10 and pass that text to Decimal.parse. To request an integral BigInt from a Decimal, pass its canonical text to BigInt.parse with radix 10. Fractional decimal text is rejected by that integer parser.

    Converting through explicitly chosen text follows the corresponding text parser. Decimal.parse never recovers decimal digits that were lost in an earlier binary float calculation.

    Причина

    Exact integer conversion and checked narrowing communicate different intentions. Option exposes fractions and overflow without selecting a rounding policy for the caller. Explicit text composition handles arbitrary precision integer exchange through the existing parsers without adding another conversion API.

    Convert both int endpoints and reject fractions or overflow

    Ссылка
    main.tpzConvert both int endpoints and reject fractions or overflowОткрыть песочницу →
    1. import std.decimal { Decimal }
    2. import std.test
    3. import std.io
    4. function read(text: string) -> Decimal {
    5. let parsed: Option<Decimal> = Decimal.parse(text)
    6. let value: Decimal = test.assertSome(parsed)
    7. return value
    8. }
    9. for text in (["-9223372036854775808", "9223372036854775807", "-9223372036854775809", "9223372036854775808", "1.000", "1.001", "-1.001", "-0.000"]) {
    10. let value: Decimal = read(text)
    11. match (value.toInt()) {
    12. case Some(integer) => io.writeLine("{integer}")
    13. case None() => io.writeLine("not an int")
    14. }
    15. }
    16. let large: Decimal = read("1000000000000000000000000000000")
    17. let narrowed: Option<int> = large.toInt()
    18. test.assertNone(narrowed)
    19. io.writeLine(large.toString())
    Ожидаемый выводКод завершения 0
    -9223372036854775808
    9223372036854775807
    not an int
    not an int
    1
    not an int
    not an int
    0
    1000000000000000000000000000000
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. -9223372036854775808
    2. 9223372036854775807
    3. not an int
    4. not an int
    5. 1
    6. not an int
    7. not an int
    8. 0
    9. 1000000000000000000000000000000

    Convert int values to exact scale zero decimals

    Ссылка
    main.tpzConvert int values to exact scale zero decimalsОткрыть песочницу →
    1. import std.decimal { Decimal }
    2. import std.test
    3. import std.io
    4. let integers: Array<int> = [-9223372036854775807 - 1, -1, 0, 1, 9223372036854775807]
    5. for integer in (integers) {
    6. let value: Decimal = integer.toDecimal()
    7. let narrowed: Option<int> = value.toInt()
    8. let recovered: int = test.assertSome(narrowed)
    9. test.assertEq(recovered, integer)
    10. io.writeLine("{value.toString()} {value.scale()}")
    11. }
    Ожидаемый выводКод завершения 0
    -9223372036854775808 0
    -1 0
    0 0
    1 0
    9223372036854775807 0
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. -9223372036854775808 0
    2. -1 0
    3. 0 0
    4. 1 0
    5. 9223372036854775807 0

    Exchange arbitrary precision integers through explicit decimal text

    Ссылка
    main.tpzExchange arbitrary precision integers through explicit decimal textОткрыть песочницу →
    1. import std.decimal { Decimal }
    2. import std.bigint { BigInt }
    3. import std.test
    4. import std.io
    5. let parsedInteger: Option<BigInt> = BigInt.parse("123456789012345678901234567890", 10)
    6. let integer: BigInt = test.assertSome(parsedInteger)
    7. let parsedDecimal: Option<Decimal> = Decimal.parse(integer.toString(10))
    8. let value: Decimal = test.assertSome(parsedDecimal)
    9. io.writeLine(value.toString())
    10. let parsedAgain: Option<BigInt> = BigInt.parse(value.toString(), 10)
    11. let recovered: BigInt = test.assertSome(parsedAgain)
    12. let equal = recovered == integer
    13. io.writeLine("{equal}")
    14. let parsedFraction: Option<Decimal> = Decimal.parse("1.5")
    15. let fraction: Decimal = test.assertSome(parsedFraction)
    16. let integral: Option<BigInt> = BigInt.parse(fraction.toString(), 10)
    17. match (integral) {
    18. case None() => io.writeLine("fraction rejected")
    19. case Some(_) => io.writeLine("converted")
    20. }
    Ожидаемый выводКод завершения 0
    123456789012345678901234567890
    true
    fraction rejected
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 123456789012345678901234567890
    2. true
    3. fraction rejected

    Меню

    Загрузка →