SCARP v0.0.6-alpha.20

Decimal literals versus float

The d suffix selects exact base-ten arithmetic.

Compiler: published alpha.20 · b1a9347f93540fdf95b0ddecba4adc55a3b4bb98

Original Scarp by Example teaching program (MIT), executed by the pinned compiler.

Predict before running

Why does adding 0.1d three times produce exactly 0.3?

decimal_literals.srp

// Exact decimal literals are opt-in; ordinary floats remain binary64.
bind subtotal: decimal = 12.50d + 0.25d;
print(subtotal);
print(0.1d + 0.2d == 0.3d);
print(0.1 + 0.2);
print(decimal_format(subtotal, 2, "half_even"));
var running = 0d;
repeat 3 as index { running += 0.1d; }
print(running);

decimal_literals.stdout

12.75
true
0.30000000000000004
12.75
0.3

Run on your computer

scarp verify tutorials/alpha20-exact-values/decimal_literals.srp
scarp exec tutorials/alpha20-exact-values/decimal_literals.srp

The website does not execute code in your browser. Compare local output against the fixture.

हिन्दी में अभ्यास

0.1d को तीन बार जोड़ने पर ठीक 0.3 क्यों मिलता है?