1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | import * as semver from "semver";
|
8 | import {MoneyUtilException} from "./exceptions";
|
9 | const nodeVersion = semver.clean(process.version);
|
10 |
|
11 | export class MoneyUtils {
|
12 | public static toTRY(amount: number): string {
|
13 | let formatted: string;
|
14 | if (semver.lt(nodeVersion, "4.0.0")) {
|
15 | formatted = (Math.round(amount * 100) / 100).toString();
|
16 | const split: string[] = formatted.split(".");
|
17 | if (split.length === 1 || split[1].length < 1) {
|
18 | split[1] = "00";
|
19 | }
|
20 | else if (split[1].length < 2) {
|
21 | split[1] = split[1] + "0";
|
22 | }
|
23 | formatted = split.join(",");
|
24 | }
|
25 | else {
|
26 | formatted = amount.toLocaleString("tr-TR", {style: "currency", currency: "TRY", currencyDisplay: "code"});
|
27 | formatted = formatted.replace(/TRY|,|\s+/gi, "");
|
28 | formatted = formatted.replace(/\./i, ",");
|
29 | }
|
30 | return MoneyUtils.validate(formatted);
|
31 | }
|
32 |
|
33 | public static toNumber(amount: string): number {
|
34 | let formatted: string = MoneyUtils.validate(amount).replace(",", ".");
|
35 | formatted = formatted.replace(/[^\d\.]/i, "");
|
36 | return parseFloat(formatted);
|
37 | }
|
38 |
|
39 | public static validate(amount: string): string {
|
40 | const split: string[] = amount.split(",");
|
41 | if (amount.indexOf(".") > -1 || split.length !== 2 || split[1].length !== 2) {
|
42 | throw new MoneyUtilException("Input validation error.");
|
43 | }
|
44 | return amount;
|
45 | }
|
46 | } |
\ | No newline at end of file |