- Forward


Truncation
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back Forward
  • The Idea:
    • Sometimes integers have more digits of accuracy than are needed
  • An Example:
    • Employees are paid a fixed amount per piece, but only for multiples of 10 pieces (e.g., an employee will get paid for 520 pieces whether they make 520, 521, or 529 pieces)
Review
Back Forward
  • A Related Situation:
    • Employees are paid per batch of ten (rather than per piece)
  • Solving this Problem:
    • We can find the number of batches by dividing by 10 (using integer division)
  • An Example:
    • 526 pieces is 526 / 10 or 52 batches
Thinking About the Problem
Back Forward
  • What We Now Know:
    • The size of a batch
    • The number of batches
  • What We Want:
    • Can easily be obtained from these two values
The Pattern
Back Forward
  • Notation:
    • place denotes the place to truncate to (10 for the 10s place, 100 for the 100s places, etc...)
    • number denotes the original number
  • The Process:
    • javaexamples/programmingpatterns/Truncation.java (Fragment: pattern)
       
Examples
Back Forward
  • The Situation:
    • Someone was born in 1996
    • We are concerned with the decade and century when they are 87 years old (i.e., in 2083)
  • Truncating:
    • To the decade: ((1996 + 87) / 10) * 10 or 2080
    • To the century: ((1996 + 87) / 100) * 100 or 2000
Some Warnings
Back Forward
  • Be Careful with Integer Arithmetic:
    • In general, (a / b) * b does not equal a
  • Be Careful about Terminology:
    • Truncating floating point values to integer values requries a different process (i.e., type casting)
  • Don't Confuse Accuracy of Calculations and Output:
    • In some situations it is necessary to perform calculations using truncated values
    • In some situations it is necessary to perform calculations using all of the digits of accuracy available and truncate at the end
    • In some situations it is necessary to perform calculations using all of the digits of accuracy available and then format the output with fewer digits of accuracy when it is displayed
There's Always More to Learn
Back -