R — Integer vectors and arithmetic
R’s %/% operator gives the floor quotient and %% gives the corresponding remainder. For positive prices in cents they separate whole dollars from the leftover cents.
A simple example
Change a stored number
- Start with n starts at 2
- Do this Add 1 to n
- Result 3
n <- 2
n <- n + 1
cat(n, "\n", sep = "")
3
Calculate a receipt in cents
The L suffix creates an integer literal. Whole-number division and remainder are vectorized in R. sprintf formats the parts and cat writes the resulting text without a printed vector index.
A student buys three notebooks at 125 cents each. Add the 50-cent delivery charge once for the whole order. Keeping the arithmetic in cents makes the total easy to check against the receipt.
Run the example
R 4. Run these commands from the directory containing the example.
Rscript Lesson.R
price_cents <- 125L
quantity <- 3L
total <- price_cents * quantity + 50L
cat(sprintf("%d.%02d\n", total %/% 100L, total %% 100L))
4.25
Three items at 125 cents cost 375 cents. Adding one 50-cent delivery charge gives 425 cents. The quotient and remainder on division by 100 give 4 dollars and 25 cents.
Try it yourself
What happens if each item costs 101 cents?
Check your answer
Three items plus delivery cost 353 cents, so the output becomes 3.53.