Skip to content

A CSV report

This program reads a file of sales. Each line has a product, a quantity and a price. The program prints the total amount for each product.

<?nvs
// This program reads a CSV file of sales and prints the total for each product.
class Report
{
// Returns the total amount for each product, with the product name as the key.
public static function totals(string $path): array<float>
{
array<float> $totals = [];
// `{ header: true }` uses the first line as the column names.
foreach (Core\Csv::parse(Core\IO::readText($path), { header: true }) as array<string> $row) {
string $product = $row['product'];
float $amount = ($row['qty'] as int) * ($row['price'] as float);
$totals[$product] = ($totals[$product] ?? 0.0) + $amount;
}
return $totals;
}
}
// The program writes a small file first, so that it runs as it is.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'sales.csv');
Core\IO::write($path, "product,qty,price\nfig,2,3.50\napple,10,0.40\nfig,1,3.50\n");
foreach (Report::totals($path) as string $product => float $total) {
echo Core\Str::padEnd($product, 8), Core\Math::round($total, { precision: 2 }), "\n";
}
Output
fig 10.5
apple 4

Run it with nvs run csv-report.nvs. It needs no nvs.toml. To allow it only one folder, write that folder in [capabilities.fs] read.

Core\IO::readText reads the whole file as a string. Core\Csv::parse splits that string into rows. With { header: true }, each row is an array with the column names as keys.

Every field in a CSV file is a string. as int and as float convert the quantity and the price to numbers. If a field is not a number, the conversion throws an error and the program stops.

$totals is an array with the product names as keys. $totals[$product] ?? 0.0 gives 0.0 the first time a product appears.

To read your own file, replace the path and remove the line that writes the sample file.