(upbeat music)
- [Instructor] All right, let's examine my code
for this challenge.
We needed to add a new column to the inventory data
to calculate the margin
between the consumer prices and wholesale prices.
So I already have two functions
for reading and writing the CSV data.
So I just needed to write the code
to perform the calculations.
My code starts by reading the Inventory.CSV file,
and then I get the first row of the result,
which is the row of headers.
So I add the new string margin on the end of that list.
That's the easy part, all right?
So then I use an array slice
to get the rows from one until the end of the file.
So this is all the data, right?
This is all the data after the headers.
So for each one of these rows, I loop over
and I calculate the difference
between the values at index four and index three.
And I cast each one of those to a decimal object.
And you can see that if I scroll back up,
I imported the decimal class from the decimal module,
and I'll get to that in a second.
So I calculate the difference
and then I add that value onto the end
of the existing row of the data
and then I just simply write out my array
to the output CSV file.
Now, the reason I need to cast each of these strings
to a decimal value
in order to preserve the floating point precision
of the currency,
and this was the hint that I gave in the previous value,
you could have just cast each of these values
to floating point numbers,
but that actually results in a loss of precision.
So let's see what happens when we do that.
I'm going to change this to float.
All right?
And I'm going to run the code again, all right?
And when I do that, if we look at the output file,
look at the difference, right?
There's all these zeros
and then some teeny tiny little, you know, decimal point
on the end.
You know, in this case, it's, you know, really large.
Some aren't affected that much,
but some, they have all these extra decimals in them, right?
Now, this is not a bug, just to be clear.
This is not a Python bug or anything.
It's a result of how computers store floating point numbers.
So to prevent this from happening,
when we work with currency values,
we use the decimal module,
which I've imported right here at the top, right?
We use the decimal module to preserve currency precision.
And you can learn more about this module,
just go into the Python documentation
and it'll explain how the decimal module works.
All right, so that's my solution.
How does my code compare to yours?