본문으로 건너뛰기
토파즈6.0 · 출시 전
다운로드 →

문서 검색

명세 6.0

방향키로 결과를 고르고 Enter를 눌러 여세요.

API 이름, 진단 번호, 규칙 또는 프로젝트 주제를 입력하세요.

    라이브러리

    std.decimal

    Compute exact decimal quantities and choose explicit rounding and conversion boundaries.

    이 모듈의 API

    12개 API

    이름모듈
    Decimal.div →std.decimal →
    Decimal.parse →std.decimal →
    Decimal.round →std.decimal →
    Decimal.scale →std.decimal →
    Decimal.toInt →std.decimal →
    Decimal.toString →std.decimal →
    RoundingMode.AwayFromZero →std.decimal →
    RoundingMode.Down →std.decimal →
    RoundingMode.HalfEven →std.decimal →
    RoundingMode.HalfUp →std.decimal →
    RoundingMode.TowardZero →std.decimal →
    RoundingMode.Up →std.decimal →

    Module

    링크

    Decimal preserves exact finite decimal values with canonical scale. Parse complete decimal text, compare exact quantities, convert integers explicitly, and choose a result grid with round or div. RoundingMode supplies six distinct rounding policies.

    Why

    링크

    Decimal arithmetic makes precision, scale and rounding explicit for exact decimal quantities. Numeric values stay independent of display padding, and different rounding intentions retain distinct modes.

    Availability

    링크

    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.

    Exported types

    링크

    export type Decimal = Decimal

    export type RoundingMode = RoundingMode

    Type members keep the compiler-owned type name shown in their declarations. Importing a module does not create a new type identity.

    Public API

    링크

    Decimal.div →

    Decimal.parse →

    Decimal.round →

    Decimal.scale →

    Decimal.toInt →

    Decimal.toString →

    RoundingMode.AwayFromZero →

    RoundingMode.Down →

    RoundingMode.HalfEven →

    RoundingMode.HalfUp →

    RoundingMode.TowardZero →

    RoundingMode.Up →

    Pending contracts

    링크

    Preserve exact decimal values and canonical scale

    링크
    규칙topaz.stdlib.contract.decimal-values.rule

    Preserve exact decimal values and canonical scale

    A Decimal represents a signed integer coefficient multiplied by ten raised to the negative scale. The coefficient has arbitrary precision. The scale is an integer from 0 through 4294967295 inclusive.

    Decimal has no fixed significant digit limit or ambient precision context. Increasing the coefficient beyond the int range does not cause numeric overflow. Decimal values are finite and have no infinity or NaN.

    Every Decimal is canonical. Remove trailing coefficient zeros while its scale is positive. Zero has coefficient zero and scale zero. A negative zero spelling produces the same value as zero.

    Decimal.scale returns the canonical scale as int. It counts fractional decimal places after normalization. It does not retain input padding or a requested display precision.

    Decimal.toString returns exact ASCII decimal text without an exponent or locale rules. A negative nonzero value starts with a minus sign. The integer part has at least one digit and no redundant leading zeros.

    A positive scale produces a decimal point followed by exactly that many fractional digits. There are no trailing fractional zeros. Scale zero omits the decimal point, and zero is written as 0.

    Exact addition and subtraction align the operand scales before combining their coefficients. Exact multiplication multiplies their coefficients and adds their scales without rounding.

    Normalize the exact product before enforcing the scale limit. Raise TPZ4004 when its canonical scale exceeds 4294967295. An intermediate scale sum must not reject a product whose canonical scale fits.

    Parsing the output of Decimal.toString recovers the same Decimal. A request for more fractional places through round or div does not append stored zeros.

    Decimal values are immutable. Receiver and positional argument expressions evaluate once in source order. An earlier fault prevents later evaluation. The decimal operations themselves do not perform external effects.

    이유

    Exact coefficients preserve decimal quantities without a hidden precision setting. Canonical scale makes equality and text exchange independent of input padding. Display padding has a separate formatting intent and is not stored as numeric value state. Scale bounds apply to the value that the operation returns. A temporary representation has no distinct numeric intent and must not make an otherwise representable product fail.

    Normalize signs and redundant decimal zeros

    링크
    main.tpzNormalize signs and redundant decimal zeros플레이그라운드 열기 →
    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 (["0", "-0.000", "+00012.3400", ".0050", "100.000"]) {
    10. let value: Decimal = read(text)
    11. io.writeLine("{value.toString()} {value.scale()}")
    12. let reparsed: Option<Decimal> = Decimal.parse(value.toString())
    13. let recovered: Decimal = test.assertSome(reparsed)
    14. test.assertEq(recovered, value)
    15. }
    기대 출력종료 코드 0
    0 0
    0 0
    12.34 2
    0.005 3
    100 0
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 0 0
    2. 0 0
    3. 12.34 2
    4. 0.005 3
    5. 100 0

    Keep every digit beyond machine integer precision

    링크
    main.tpzKeep every digit beyond machine integer precision플레이그라운드 열기 →
    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. let left: Decimal = read("1000000000000000000000000000000.25")
    10. let right: Decimal = read("0.75")
    11. let sum: Decimal = left + right
    12. let difference: Decimal = left - right
    13. let product: Decimal = left * right
    14. io.writeLine(sum.toString())
    15. io.writeLine(difference.toString())
    16. io.writeLine(product.toString())
    17. io.writeLine(left.toString())
    기대 출력종료 코드 0
    1000000000000000000000000000001
    999999999999999999999999999999.5
    750000000000000000000000000000.1875
    1000000000000000000000000000000.25
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 1000000000000000000000000000001
    2. 999999999999999999999999999999.5
    3. 750000000000000000000000000000.1875
    4. 1000000000000000000000000000000.25

    Normalize a product before checking its final scale

    링크
    main.tpzNormalize a product before checking its final scale플레이그라운드 열기 →
    1. import std.decimal { Decimal }
    2. import std.test
    3. import std.io
    4. let parsedPlace: Option<Decimal> = Decimal.parse("0.1")
    5. let mut place: Decimal = test.assertSome(parsedPlace)
    6. let mut smallest: Decimal = (1).toDecimal()
    7. let mut step: int = 0
    8. while (step < 32) {
    9. smallest = smallest * place
    10. if (step < 31) {
    11. place = place * place
    12. }
    13. step = step + 1
    14. }
    15. let doubled: Decimal = smallest * (2).toDecimal()
    16. let parsedHalf: Option<Decimal> = Decimal.parse("0.5")
    17. let half: Decimal = test.assertSome(parsedHalf)
    18. let recovered: Decimal = doubled * half
    19. let equal = recovered == smallest
    20. io.writeLine("{recovered.scale()} {equal}")
    기대 출력종료 코드 0
    4294967295 true
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 4294967295 true

    Parse complete finite decimal text

    링크
    규칙topaz.stdlib.contract.decimal-parse.rule

    Parse complete finite decimal text

    Decimal.parse reads the complete input string. Text starts with an optional ASCII plus or minus sign. The remaining text contains ASCII digits and at most one decimal point.

    Without a decimal point, at least one digit is required. With a decimal point, at least one digit must follow it and the integer digits may be absent. The strings .5 and -.5 are accepted. The strings 1. and . are rejected.

    Leading integer zeros and trailing fractional zeros are accepted. Their exact numeric value is normalized by the decimal value rule. An accepted sign on zero does not survive normalization.

    The input may contain at most 4294967295 fractional digits before normalization. A larger fractional digit count returns None(). The integer digit count has no fixed numeric precision limit.

    Whitespace, non-ASCII digits, separators, radix prefixes, exponents, NaN and infinity spellings are rejected. Parsing does not trim, remove separators, stop at a valid prefix, or convert through a binary float.

    Valid text returns Some containing the exact Decimal. Every malformed spelling returns None() without a numeric conversion fault or replacement value.

    This grammar describes text data passed to Decimal.parse. Numeric literal spelling follows the language literal rules.

    이유

    A complete decimal data grammar makes accepted input predictable and preserves every digit. Optional signs and a missing integer zero are accepted input conventions. Canonical output still gives each value one serialized spelling.

    Accept explicit signs and fractional decimal text

    링크
    main.tpzAccept explicit signs and fractional decimal text플레이그라운드 열기 →
    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 (["7", "+7", "-7", "0007", ".5", "-.5", "+.5", "01.0200"]) {
    10. let value: Decimal = read(text)
    11. io.writeLine(value.toString())
    12. }
    기대 출력종료 코드 0
    7
    7
    -7
    7
    0.5
    -0.5
    0.5
    1.02
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 7
    2. 7
    3. -7
    4. 7
    5. 0.5
    6. -0.5
    7. 0.5
    8. 1.02

    Reject incomplete and nondecimal spellings

    링크
    main.tpzReject incomplete and nondecimal spellings플레이그라운드 열기 →
    1. import std.decimal { Decimal }
    2. import std.io
    3. for text in (["", "+", "-", ".", "+.", "-.", "1.", "1.2.3", "1e2", "1E+2", "0x10", "1_000", "1,2", "NaN", "Infinity", " 1", "1 ", "1.2", "١.٢", "1\n2", "\t1"]) {
    4. match (Decimal.parse(text)) {
    5. case None() => io.writeLine("rejected")
    6. case Some(_) => io.writeLine("accepted")
    7. }
    8. }
    기대 출력종료 코드 0
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    rejected
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. rejected
    2. rejected
    3. rejected
    4. rejected
    5. rejected
    6. rejected
    7. rejected
    8. rejected
    9. rejected
    10. rejected
    11. rejected
    12. rejected
    13. rejected
    14. rejected
    15. rejected
    16. rejected
    17. rejected
    18. rejected
    19. rejected
    20. rejected
    21. rejected

    Choose a decimal grid and a rounding direction

    링크
    규칙topaz.stdlib.contract.decimal-round.rule

    Choose a decimal grid and a rounding direction

    For a requested scale s, rounding selects a multiple of ten raised to negative s. A value already on that grid is unchanged in every rounding mode.

    The requested scale must be an int from 0 through 4294967295 inclusive. A negative value or a value above that range raises TPZ5001 during execution. Scale is never clamped or interpreted as digits to the left of the decimal point.

    When the requested scale is at least the canonical scale, round returns the same value. Otherwise it chooses a grid value according to the supplied mode and normalizes the result.

    RoundingMode.Down() chooses the greatest grid value no greater than the input. It rounds toward negative infinity, including at a midpoint.

    RoundingMode.Up() chooses the least grid value no smaller than the input. It rounds toward positive infinity, including at a midpoint.

    RoundingMode.TowardZero() chooses the grid value with smaller absolute magnitude when the input is between two grid values. RoundingMode.AwayFromZero() chooses the one with larger absolute magnitude. These directions also apply at midpoints.

    RoundingMode.HalfUp() chooses the nearer grid value. At an exact midpoint it chooses the value with greater absolute magnitude for either sign.

    RoundingMode.HalfEven() chooses the nearer grid value. At an exact midpoint it chooses the value whose integer coefficient on the requested grid is even. Determine parity before canonical trailing zeros are removed.

    Omitting the mode selects RoundingMode.HalfEven(). The default is independent of host settings and applies equally to positive and negative values.

    A carry may reduce the canonical scale. A rounded zero has scale zero and no negative sign. Rounding does not pad the result to the requested scale.

    Each RoundingMode spelling constructs a distinct zero payload enum variant and uses parentheses. The modes are immutable values that callers may store and pass to both round and div.

    이유

    A decimal grid states which precision the caller needs. Nearest rounding, an upper or lower bound, and movement toward or away from zero express different numeric intentions. Their results can agree for some inputs without making their meanings interchangeable. HalfEven gives exact ties a stable rule without consistently favoring one magnitude direction.

    Resolve positive and negative ties in every rounding mode

    링크
    main.tpzResolve positive and negative ties in every rounding mode플레이그라운드 열기 →
    1. import std.decimal { Decimal, RoundingMode }
    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. function rounded(text: string, mode: RoundingMode) -> string {
    10. let value: Decimal = read(text)
    11. return value.round(0, mode).toString()
    12. }
    13. let modes: Array<RoundingMode> = [RoundingMode.Down(), RoundingMode.Up(), RoundingMode.TowardZero(), RoundingMode.AwayFromZero(), RoundingMode.HalfUp(), RoundingMode.HalfEven()]
    14. for mode in (modes) {
    15. let a = rounded("2.5", mode)
    16. let b = rounded("3.5", mode)
    17. let c = rounded("-2.5", mode)
    18. let d = rounded("-3.5", mode)
    19. io.writeLine("{a} {b} {c} {d}")
    20. }
    기대 출력종료 코드 0
    2 3 -3 -4
    3 4 -2 -3
    2 3 -2 -3
    3 4 -3 -4
    3 4 -3 -4
    2 4 -2 -4
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 2 3 -3 -4
    2. 3 4 -2 -3
    3. 2 3 -2 -3
    4. 3 4 -3 -4
    5. 3 4 -3 -4
    6. 2 4 -2 -4

    Distinguish directed rounding from nearest rounding

    링크
    main.tpzDistinguish directed rounding from nearest rounding플레이그라운드 열기 →
    1. import std.decimal { Decimal, RoundingMode }
    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. function rounded(text: string, mode: RoundingMode) -> string {
    10. let value: Decimal = read(text)
    11. return value.round(0, mode).toString()
    12. }
    13. let modes: Array<RoundingMode> = [RoundingMode.Down(), RoundingMode.Up(), RoundingMode.TowardZero(), RoundingMode.AwayFromZero(), RoundingMode.HalfUp(), RoundingMode.HalfEven()]
    14. for mode in (modes) {
    15. let a = rounded("2.1", mode)
    16. let b = rounded("2.9", mode)
    17. let c = rounded("-2.1", mode)
    18. let d = rounded("-2.9", mode)
    19. io.writeLine("{a} {b} {c} {d}")
    20. }
    기대 출력종료 코드 0
    2 2 -3 -3
    3 3 -2 -2
    2 2 -2 -2
    3 3 -3 -3
    2 3 -2 -3
    2 3 -2 -3
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 2 2 -3 -3
    2. 3 3 -2 -2
    3. 2 2 -2 -2
    4. 3 3 -3 -3
    5. 2 3 -2 -3
    6. 2 3 -2 -3

    Apply the default mode and normalize a carry or zero

    링크
    main.tpzApply the default mode and normalize a carry or zero플레이그라운드 열기 →
    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. let value: Decimal = read("1.245")
    10. io.writeLine(value.round(2).toString())
    11. io.writeLine(read("1.255").round(2).toString())
    12. io.writeLine(value.round(5).toString())
    13. let carry: Decimal = read("9.995").round(2)
    14. let zero: Decimal = read("-0.004").round(2)
    15. io.writeLine("{carry.toString()} {carry.scale()}")
    16. io.writeLine("{zero.toString()} {zero.scale()}")
    17. io.writeLine(value.toString())
    기대 출력종료 코드 0
    1.24
    1.26
    1.245
    10 0
    0 0
    1.245
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 1.24
    2. 1.26
    3. 1.245
    4. 10 0
    5. 0 0
    6. 1.245

    Accept the largest scale without adding stored zeros

    링크
    main.tpzAccept the largest scale without adding stored zeros플레이그라운드 열기 →
    1. import std.decimal { Decimal }
    2. import std.test
    3. import std.io
    4. let one: Decimal = (1).toDecimal()
    5. let zero: Decimal = (0).toDecimal()
    6. let same: Decimal = one.round(4294967295)
    7. let sameZero: Decimal = zero.round(4294967295)
    8. io.writeLine("{same.toString()} {same.scale()}")
    9. io.writeLine("{sameZero.toString()} {sameZero.scale()}")
    기대 출력종료 코드 0
    1 0
    0 0
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 1 0
    2. 0 0

    Reject a rounding scale outside the valid range

    링크
    main.tpzReject a rounding scale outside the valid range플레이그라운드 열기 →
    1. import std.decimal { Decimal }
    2. import std.io
    3. let value: Decimal = (1).toDecimal()
    4. value.round(-1)
    5. io.writeLine("after")
    기대 출력0이 아닌 종료 코드
    표준 출력 없음.
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    거절 단계 run. 종료 코드가 0이 아닙니다.

    Reject a rounding scale outside the valid range

    링크
    main.tpzReject a rounding scale outside the valid range플레이그라운드 열기 →
    1. import std.decimal { Decimal }
    2. import std.io
    3. let value: Decimal = (1).toDecimal()
    4. value.round(4294967296)
    5. io.writeLine("after")
    기대 출력0이 아닌 종료 코드
    표준 출력 없음.
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    거절 단계 run. 종료 코드가 0이 아닙니다.

    Diagnostics

    링크

    Runtime value guard →

    Divide with an explicit result scale

    링크
    규칙topaz.stdlib.contract.decimal-division.rule

    Divide with an explicit result scale

    Decimal.div evaluates the exact quotient of its receiver and the divisor. For a nonzero divisor it rounds that quotient once to the requested decimal grid and returns Ok containing the normalized Decimal.

    The requested scale and mode have the same meaning as in Decimal.round. Omitting the mode selects RoundingMode.HalfEven(). Input scales and coefficient sizes do not introduce another precision limit or an intermediate rounding step.

    A nonterminating decimal quotient is rounded to the requested grid. A terminating quotient that is already on the grid remains exact. The canonical result scale can be smaller than the requested scale.

    Division signs follow ordinary numeric division. All six rounding modes apply to the signed exact quotient, including negative ties and results that round to zero.

    A zero divisor returns Err with the string Decimal.div: division by zero. This includes zero divided by zero and a divisor parsed from a negative zero spelling. This failure is a Result value and does not raise TPZ4002.

    A zero dividend and a nonzero divisor return Ok containing zero for every valid requested scale. An internal sum of operand and requested scales must not turn a nonzero divisor into a division by zero error.

    An invalid requested scale raises TPZ5001 during execution before the zero divisor is classified. The operation never replaces an invalid scale with zero or reports that scale error as a successful Result.

    The receiver, divisor, scale and explicitly supplied mode expressions evaluate once in that order before their values are validated. The operation preserves both operands.

    이유

    A division result needs an explicit decimal grid because a finite pair of decimals can have a nonterminating quotient. Rounding the exact quotient once avoids hidden precision loss. A recoverable zero divisor stays distinct from invalid configuration and from internal scale arithmetic.

    Distinguish exact and repeating quotients at the requested grid

    링크
    main.tpzDistinguish exact and repeating quotients at the requested grid플레이그라운드 열기 →
    1. import std.decimal { Decimal }
    2. import std.test
    3. import std.io
    4. function show(result: Result<Decimal, string>) -> () {
    5. let value: Decimal = test.assertOk(result)
    6. io.writeLine("{value.toString()} {value.scale()}")
    7. }
    8. let one: Decimal = (1).toDecimal()
    9. let third: Result<Decimal, string> = one.div((3).toDecimal(), 6)
    10. let eighth: Result<Decimal, string> = one.div((8).toDecimal(), 2)
    11. let negativeTie: Result<Decimal, string> = (-1).toDecimal().div((8).toDecimal(), 2)
    12. let exact: Result<Decimal, string> = (100).toDecimal().div((4).toDecimal(), 4)
    13. let integerGrid: Result<Decimal, string> = (2).toDecimal().div((3).toDecimal(), 0)
    14. show(third)
    15. show(eighth)
    16. show(negativeTie)
    17. show(exact)
    18. show(integerGrid)
    기대 출력종료 코드 0
    0.333333 6
    0.12 2
    -0.12 2
    25 0
    1 0
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 0.333333 6
    2. 0.12 2
    3. -0.12 2
    4. 25 0
    5. 1 0

    Apply every rounding mode to signed quotient ties

    링크
    main.tpzApply every rounding mode to signed quotient ties플레이그라운드 열기 →
    1. import std.decimal { Decimal, RoundingMode }
    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. function quotient(text: string, mode: RoundingMode) -> string {
    10. let value: Decimal = read(text)
    11. let result: Result<Decimal, string> = value.div((2).toDecimal(), 0, mode)
    12. let rounded: Decimal = test.assertOk(result)
    13. return rounded.toString()
    14. }
    15. let modes: Array<RoundingMode> = [RoundingMode.Down(), RoundingMode.Up(), RoundingMode.TowardZero(), RoundingMode.AwayFromZero(), RoundingMode.HalfUp(), RoundingMode.HalfEven()]
    16. for mode in (modes) {
    17. let a = quotient("5", mode)
    18. let b = quotient("7", mode)
    19. let c = quotient("-5", mode)
    20. let d = quotient("-7", mode)
    21. io.writeLine("{a} {b} {c} {d}")
    22. }
    기대 출력종료 코드 0
    2 3 -3 -4
    3 4 -2 -3
    2 3 -2 -3
    3 4 -3 -4
    3 4 -3 -4
    2 4 -2 -4
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 2 3 -3 -4
    2. 3 4 -2 -3
    3. 2 3 -2 -3
    4. 3 4 -3 -4
    5. 3 4 -3 -4
    6. 2 4 -2 -4

    Return a recoverable error for every zero divisor

    링크
    main.tpzReturn a recoverable error for every zero divisor플레이그라운드 열기 →
    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. let divisor: Decimal = read("-0.000")
    10. let numerators: Array<Decimal> = [(0).toDecimal(), (1).toDecimal()]
    11. for numerator in (numerators) {
    12. let result: Result<Decimal, string> = numerator.div(divisor, 2)
    13. match (result) {
    14. case Err(message) => io.writeLine(message)
    15. case Ok(_) => io.writeLine("accepted")
    16. }
    17. }
    18. io.writeLine(divisor.toString())
    기대 출력종료 코드 0
    Decimal.div: division by zero
    Decimal.div: division by zero
    0
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. Decimal.div: division by zero
    2. Decimal.div: division by zero
    3. 0

    Keep a zero quotient at the largest valid scale

    링크
    main.tpzKeep a zero quotient at the largest valid scale플레이그라운드 열기 →
    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. let divisor: Decimal = read("0.1")
    10. let result: Result<Decimal, string> = (0).toDecimal().div(divisor, 4294967295)
    11. match (result) {
    12. case Ok(value) => io.writeLine(value.toString())
    13. case Err(_) => io.writeLine("unexpected error")
    14. }
    기대 출력종료 코드 0
    0
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 0

    Evaluate the receiver and division arguments once in order

    링크
    main.tpzEvaluate the receiver and division arguments once in order플레이그라운드 열기 →
    1. import std.decimal { Decimal, RoundingMode }
    2. import std.test
    3. import std.io
    4. function receiver() -> Decimal {
    5. io.writeLine("receiver")
    6. return (6).toDecimal()
    7. }
    8. function divisor() -> Decimal {
    9. io.writeLine("divisor")
    10. return (4).toDecimal()
    11. }
    12. function scale() -> int {
    13. io.writeLine("scale")
    14. return 1
    15. }
    16. function mode() -> RoundingMode {
    17. io.writeLine("mode")
    18. return RoundingMode.HalfEven()
    19. }
    20. let result: Result<Decimal, string> = receiver().div(divisor(), scale(), mode())
    21. let value: Decimal = test.assertOk(result)
    22. io.writeLine(value.toString())
    기대 출력종료 코드 0
    receiver
    divisor
    scale
    mode
    1.5
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. receiver
    2. divisor
    3. scale
    4. mode
    5. 1.5

    Reject an invalid scale before classifying a zero divisor

    링크
    main.tpzReject an invalid scale before classifying a zero divisor플레이그라운드 열기 →
    1. import std.decimal { Decimal }
    2. import std.io
    3. let value: Decimal = (1).toDecimal()
    4. value.div((0).toDecimal(), -1)
    5. io.writeLine("after")
    기대 출력0이 아닌 종료 코드
    표준 출력 없음.
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    거절 단계 run. 종료 코드가 0이 아닙니다.

    Reject an invalid scale before classifying a zero divisor

    링크
    main.tpzReject an invalid scale before classifying a zero divisor플레이그라운드 열기 →
    1. import std.decimal { Decimal }
    2. import std.io
    3. let value: Decimal = (1).toDecimal()
    4. value.div((0).toDecimal(), 4294967296)
    5. io.writeLine("after")
    기대 출력0이 아닌 종료 코드
    표준 출력 없음.
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    거절 단계 run. 종료 코드가 0이 아닙니다.

    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

    Compare exact decimal values independently of input scale

    링크
    규칙topaz.stdlib.contract.decimal-comparison.rule

    Compare exact decimal values independently of input scale

    Decimal equality compares exact numeric values. Values parsed from 1.2, 1.20 and 1.200 are equal. Redundant scale in an input spelling is not part of value identity.

    The equality operators == and != return complementary results. Zero and every accepted signed or padded zero spelling compare equal.

    The ordering operators <, <=, > and >= use exact numeric order. They align decimal places without first rounding either operand or converting either operand to float.

    Every pair of Decimal values is comparable. Equality agrees with ordering, and exactly one of less than, equal to or greater than holds.

    Comparison leaves both operands and their canonical scales unchanged. Call round explicitly when comparison after rounding is the intended operation.

    이유

    Numeric comparison answers whether quantities are equal or ordered. Retaining textual padding as a second value identity would mix formatting intent into arithmetic. Exact comparison also preserves distinctions beyond binary floating point precision.

    Treat values with different input padding as equal

    링크
    main.tpzTreat values with different input padding as equal플레이그라운드 열기 →
    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. let left: Decimal = read("1.20")
    10. let right: Decimal = read("1.2000")
    11. let equal = left == right
    12. let unequal = left != right
    13. let less = left < right
    14. let lessOrEqual = left <= right
    15. let greater = left > right
    16. let greaterOrEqual = left >= right
    17. io.writeLine("{equal} {unequal} {less} {lessOrEqual} {greater} {greaterOrEqual}")
    18. io.writeLine("{left.scale()} {right.scale()}")
    기대 출력종료 코드 0
    true false false true false true
    1 1
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. true false false true false true
    2. 1 1

    Order neighboring large values and signed zero exactly

    링크
    main.tpzOrder neighboring large values and signed zero exactly플레이그라운드 열기 →
    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. let lower: Decimal = read("9007199254740992")
    10. let higher: Decimal = read("9007199254740993")
    11. let increasing = lower < higher
    12. let decreasing = higher > lower
    13. let distinct = lower != higher
    14. let negativeOrder = -higher < -lower
    15. io.writeLine("{increasing} {decreasing} {distinct} {negativeOrder}")
    16. let negativeZero: Decimal = read("-0.000")
    17. let zero: Decimal = (0).toDecimal()
    18. let sameZero = negativeZero == zero
    19. io.writeLine("{sameZero}")
    기대 출력종료 코드 0
    true true true true
    true
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. true true true true
    2. true

    메뉴

    다운로드 →