Search⌘ K
AI Features

Managing Data Conversions II

Explore techniques for converting string data into numeric types and back, focusing on fixed-width formats. Learn to format currency values with precision, remove redundant decimal separators, and parse invoice totals using substring methods to accurately retrieve original data values.

We worked to convert our string data back into our original records. We used PHP’s intval and floatval functions to convert our strings into PHP data types. Converting our initial data into strings and then from strings back into floats and integers are examples of data conversion. It is relatively rare that data will be stored strictly as-is without any conversion process.

Formatting numbers when converting invoice data

Let’s revisit the idea of converting our invoice data into a fixed-width string format. Still, instead of simply encoding everything as a string, let’s decide that all financial data, such as our total, will be stored with trailing ...

PHP
<?php
$textData = collect($invoices)->map(function ($invoice) {
$totalFormatted = number_format($invoice['total'], 2);
return str('')
->append(str($invoice['number'])->padLeft(10))
->append(str($totalFormatted)->padLeft(10))
->append(str($invoice['quantity'])->padLeft(10))
->append(str($invoice['pid'])->padLeft(10));
})->join('');

Now, when we convert our invoice array into a data string, we ...