Wiki source code of Price Formatting Guide
Show last authors
author | version | line-number | content |
---|---|---|---|
1 | 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. | ||
2 | |||
3 | = Formatting Rules and Data = | ||
4 | |||
5 | For formatting a price we need the following data: | ||
6 | |||
7 | * **thousands separator** - . or , depending on the country | ||
8 | * **decimal point** - , or . depending on the country | ||
9 | * **currency symbol** - € or other depending on the currency | ||
10 | * **price pattern** - currency symbol before or after price depending on the currency | ||
11 | * **decimal count** - 1 or 2 decimal counts depending on the currency | ||
12 | |||
13 | Where do we get the data from? Fetch your [[shop>>doc:Shop]] and fetch [[country>>doc:API.Spreadshirt Public Shop API Documentation.API REST Resources.Country.WebHome]] and [[currency>>doc:Currency]] accordingly. | ||
14 | |||
15 | = Example = | ||
16 | |||
17 | {{code}} | ||
18 | <?php | ||
19 | function formatPrice($price, $symbol, $decimalCount, $pattern, $thousandsSeparator, $decimalPoint) { | ||
20 | // formatting settings | ||
21 | $price = "" . $price; | ||
22 | |||
23 | // split integer from cents | ||
24 | $centsVal = ""; | ||
25 | $integerVal = "0"; | ||
26 | if (strpos($price, '.') != -1) { | ||
27 | $centsVal = "" .substr($price, strpos($price, '.') + 1, strlen($price) - strpos($price, '.') + 1); | ||
28 | $integerVal = "" .substr($price, 0, strpos($price, '.')); | ||
29 | } else { | ||
30 | $integerVal = $price; | ||
31 | } | ||
32 | |||
33 | $formatted = ""; | ||
34 | |||
35 | $count = 0; | ||
36 | for ($j = strlen($integerVal)-1; $j >= 0; $j--) { | ||
37 | $character = $integerVal[$j]; | ||
38 | $count++; | ||
39 | if ($count % 3 == 0) | ||
40 | $formatted = ($thousandsSeparator . $character) . $formatted; | ||
41 | else | ||
42 | $formatted = $character . $formatted; | ||
43 | } | ||
44 | if ($formatted[0] == $thousandsSeparator) | ||
45 | $formatted = substr($formatted, 1, strlen($formatted)); | ||
46 | |||
47 | $formatted .= $decimalPoint; | ||
48 | |||
49 | for ($j = 0; $j < $decimalCount; $j++) { | ||
50 | if($j < strlen($centsVal)) { | ||
51 | $formatted .= "" . $centsVal[$j]; | ||
52 | } else { | ||
53 | $formatted .= "0"; | ||
54 | } | ||
55 | } | ||
56 | |||
57 | $out = $pattern; | ||
58 | $out = str_replace('%', $formatted, $out); | ||
59 | $out = str_replace('$', $symbol, $out); | ||
60 | return $out; | ||
61 | }; | ||
62 | ?> | ||
63 | |||
64 | {{/code}} | ||
65 | |||
66 | (% class="auto-cursor-target" %) | ||
67 | \\ |