Musings of an 8-bit Vet

A Student Coders Tech Diary

Strings & Things

Two useful things I learned doing homework over the weekend:

USEFUL THING 1: git commit —amend

Lets say that your fingers get ahead of your brain, and that you write your

git commit -m "Mad code skilz"

and then realize that you forgot to add your modified file.

Well, go ahead

git add thatfile.txt

and then issue

git commit --amend

This will combine the last two commands together, your forgotten file will get linked with the commit message. Problem solved.

USEFUL THING 2: Control significant digits in Ruby float returns

While building our CashRegister class, I ran into the problem that Ruby floats return way more digits after the decimal point than you need to make change.

For example, if you pay for an $8.30 purchase with a $10 bill, you do not expect to get the message:

Your change is $1.6999999999999993

Thanks to a quick HipChat session with classmate Aron, I arrived at the following way to control float output:

puts "Your change is $#{sprintf("%0.2f",@reg_change)}"

Let’s break it down, the key part here is inside the string interpolation:


In particular, the “%0.2f” is telling sprintf that you want output to be offset by 0 digits, and include only .2 digits after the decimal point.

If you want to set the width of your float output, to say right justify, change the 0 to a larger number, 10 would include padding to make the field 10 digits wide. If you want more or less precision after the decimal, change the number after the . to any number you choose, say .1 or .5.

My final output: Your change is $1.70. Problem solved.

Thanx for reading. Stay tuned for more from the front lines…