Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
154: Precision Arithmetic for Financial Calculations
If you've spent any time in professional software engineering, you've probably heard the horror stories about floating-point errors. In a hobby project, a rounding error at the eighth decimal place is a curiosity. In a financial system, it's a bug that gets you fired or, worse, audited by the government.
Today, we're going to build a small utility to calculate a "Loyalty Discount" for an e-commerce store. The rule is simple: we take a subtotal, apply a percentage discount, and then add a flat-rate shipping fee. It sounds trivial, but the way we handle the numbers makes all the difference.
The temptation of the Double
When I first started writing this, my instinct was to just use Double. It's fast, it's built-in, and for most things, it's "close enough." Let's look at what happens when we try to calculate a 10% discount on a $19.99 item.
val subtotal = 19.99
val discountRate = 0.10
val discountAmount = subtotal * discountRate
println(s"Discount: $discountAmount")
// Output: Discount: 1.9990000000000001
There it is. That tiny ...0001 at the end. It happens because Double uses binary floating-point representation, which cannot exactly represent many decimal fractions. If you sum this up over a million transactions, your books will never balance. We need BigDecimal.
Switching to BigDecimal for Exactness
Scala's BigDecimal is a wrapper around java.math.BigDecimal. It allows us to specify the exact precision we need. I'll rewrite our logic to ensure we aren't losing pennies to the void.
val subtotal = BigDecimal("19.99")
val discountRate = BigDecimal("0.10")
val discountAmount = subtotal * discountRate
val finalPrice = subtotal - discountAmount
println(s"Final Price: $finalPrice")
// Output: Final Price: 17.991
That's better, but we have a new problem: 17.991 isn't a valid currency amount. We can't charge a customer a tenth of a cent. We need to round this to two decimal places.
The "Non-Terminating Decimal" Trap
Here is where I usually trip up when I'm rushing. I tried to divide the total by a factor to split the cost between two promotional accounts, and I did this:
val splitCost = finalPrice / BigDecimal("3")
// Result: java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
I forgot that BigDecimal is too precise. When you divide 17.991 by 3, you get a repeating decimal. Since BigDecimal tries to be exact by default, it throws an exception because it can't represent an infinite string of numbers. To fix this, we have to tell Scala how to round the result using a MathContext or the setScale method.
Polishing the Calculation Logic
Now, let's put this all together into a clean, reusable function. I'll use RoundingMode.HALF_UP, which is the standard "round half up" logic we all learned in school and that most accounting software expects.
import scala.math.BigDecimal.RoundingMode
def calculateFinalTotal(subtotal: BigDecimal, discountPercent: BigDecimal): BigDecimal = {
val discountAmount = subtotal * (discountPercent / 100)
val total = subtotal - discountAmount
// We set the scale to 2 decimal places and use HALF_UP rounding
total.setScale(2, RoundingMode.HALF_UP)
}
val myTotal = calculateFinalTotal(BigDecimal("19.99"), BigDecimal("10.0"))
println(s"The customer pays: $$${myTotal}")
// Output: The customer pays: $17.99
By explicitly defining the scale and the rounding mode, we've moved from "approximate math" to "financial math." We are now in control of every single digit.
📋 Practical Task
Build a Compound Interest Calculator for a Savings Account
Your task is to create a small program that calculates the future value of a savings account. You must avoid Double entirely to ensure financial precision.
- Create a function
calculateCompoundInterest(principal: BigDecimal, annualRate: BigDecimal, years: Int). - The formula for annual compounding is:
Future Value = Principal * (1 + Rate)^Years. - The
annualRatewill be passed as a percentage (e.g.,5.0for 5%). - The final result must be rounded to exactly 2 decimal places using
RoundingMode.HALF_UP. - Test your function with a principal of
1000.00, a rate of3.5, and a duration of10years.
There are no comments for now.