Page tree
Skip to end of metadata
Go to start of metadata

In this short guide, we will tell you how to use Spreadshirt's shop, country and currency data to format your prices correctly. This is only useful for advanced, generic implementations. If you maintain an implementation used for a single shop, you can hard code whatever works for you.

Formatting Rules and Data

For formatting a price we need the following data:

  • thousands separator - . or , depending on the country
  • decimal point - , or . depending on the country
  • currency symbol - € or other depending on the currency
  • price pattern - currency symbol before or after price depending on the currency
  • decimal count - 1 or 2 decimal counts depending on the currency

Where do we get the data from? Fetch your shop and fetch country and currency accordingly.

Example

<?php
    function formatPrice($price, $symbol, $decimalCount, $pattern, $thousandsSeparator, $decimalPoint) {
        // formatting settings
        $price = "" . $price;

        // split integer from cents
        $centsVal = "";
        $integerVal = "0";
        if (strpos($price, '.') != -1) {
            $centsVal = "" .substr($price, strpos($price, '.') + 1, strlen($price) - strpos($price, '.') + 1);
            $integerVal = "" .substr($price, 0, strpos($price, '.'));
        } else {
            $integerVal = $price;
        }

        $formatted = "";

        $count = 0;
        for ($j = strlen($integerVal)-1; $j >= 0; $j--) {
            $character = $integerVal[$j];
            $count++;
            if ($count % 3 == 0)
                $formatted = ($thousandsSeparator . $character) . $formatted;
            else
                $formatted = $character . $formatted;
        }
        if ($formatted[0] == $thousandsSeparator)
            $formatted = substr($formatted, 1, strlen($formatted));

        $formatted .= $decimalPoint;

        for ($j = 0; $j < $decimalCount; $j++) {
            if($j < strlen($centsVal)) {
                $formatted .= "" . $centsVal[$j];
            } else {
                $formatted .= "0";
            }
        }

        $out = $pattern;
        $out = str_replace('%', $formatted, $out);
        $out = str_replace('$', $symbol, $out);
        return $out;
    };
?>
  • No labels