Data Types: Decimal
● Beginner3 min
Decimal holds decimal numbers exactly, with as many digits as they need: it is Kavach's big decimal. Use it for money.
fn main() {
const price: Decimal = 499.99
const quantity: Decimal = 3
print(price * quantity)
const huge: Decimal = 99999999999999999999999999999999999999.99
const tiny: Decimal = 0.000000000000000000000000000001
print(huge + tiny)
}The program ran and printed:
kavach run money.kav
1499.9799999999999999999999999999999999999999.990000000000000000000000000001
Write the type, : Decimal, and the number is kept exactly as written. A Float would compute 0.1 + 0.2 as 0.30000000000000004 when worked out while the program runs; a Decimal gives 0.3:
fn main() {
const a = 0.1 + 0.2
print(a)
let x = 0.1
print(x + 0.2)
const price: Decimal = 0.1
const total = price + Decimal(0.2)
print(total)
}The program ran and printed:
kavach run decimal.kav
0.30.300000000000000040.3
Rounding
fn main() {
const a: Decimal = 2.345
const b: Decimal = -2.345
const c: Decimal = 2.355
print(a.round(2))
print(b.round(2))
print(a.round_even(2))
print(c.round_even(2))
}The program ran and printed:
kavach run rounding.kav
2.35-2.352.342.36
round(2)rounds to 2 places, a half away from zero:2.345becomes2.35,-2.345becomes-2.35. This is how most people round by hand.round_even(2)rounds a half to the even digit, "banker's rounding":2.345becomes2.34,2.355becomes2.36. Over many sums, halves then go up as often as down, so totals don't drift upward. Banks and statistics use it.
As big as it needs to be
There is no separate BigDecimal type to learn: a Decimal grows by itself. Up to about 38 digits it is kept in a fast 128-bit form, and beyond that it keeps every digit, with no change to your code. A division that never ends keeps 18 digits after the point.
What Kavach does for you
A number takes its type from where it goes
const price: Decimal = 499.99is an exact decimal, not a rounded float. Without a type, whole numbers areInt.Decimal never runs out of digits
A
Decimalkeeps as many digits as it needs, so money adds up to the paisa however large it gets.