UNPKG

@rzl-zone/utils-js

Version:

A modern, lightweight set of JavaScript utility functions with TypeScript support for everyday development, crafted to enhance code readability and maintainability.

64 lines (61 loc) 2.72 kB
/*! * ==================================================== * Rzl Utils-JS. * ---------------------------------------------------- * Version: 3.11.0. * Author: Rizalvin Dwiky. * Repository: https://github.com/rzl-zone/utils-js. * ==================================================== */ import { isNonEmptyString } from './chunk-MSUW5VHZ.js'; var parseCurrencyString = (input) => { if (!isNonEmptyString(input)) return 0; let trimmed = input.trim().replace(/\u00A0/g, "").replace(/\u202F/g, ""); let isNegative = false; if (/^\(.*\)$/.test(trimmed)) { isNegative = true; trimmed = trimmed.slice(1, -1).trim(); } trimmed = trimmed.replace(/^[-\s]+/, (match) => match.includes("-") ? "-" : "").replace(/[\s.,-]+$/, ""); isNegative = isNegative || /^-/.test(trimmed) || /^[^\d]*-/.test(trimmed); const cleaned = trimmed.replace(/[^0-9.,'\s]/g, ""); let cleanedNoSpace = cleaned.replace(/[\s']/g, ""); const indianMatches = cleanedNoSpace.match(/,\d{2}/g); const isIndianStyle = indianMatches && indianMatches.length > 1; if (isIndianStyle) { cleanedNoSpace = cleanedNoSpace.replace(/,/g, ""); } else { const dotCount = (cleanedNoSpace.match(/\./g) || []).length; const commaCount = (cleanedNoSpace.match(/,/g) || []).length; if (dotCount > 1 && commaCount === 0) { cleanedNoSpace = cleanedNoSpace.replace(/\./g, ""); } else if (commaCount > 1 && dotCount === 0) { cleanedNoSpace = cleanedNoSpace.replace(/,/g, ""); } else { const lastComma = cleanedNoSpace.lastIndexOf(","); const lastDot = cleanedNoSpace.lastIndexOf("."); if (lastComma > lastDot) { cleanedNoSpace = cleanedNoSpace.replace(/\./g, "").replace(",", "."); } else if (lastDot > lastComma) { cleanedNoSpace = cleanedNoSpace.replace(/,/g, ""); } else { if (lastComma > lastDot) { const beforeDecimal = cleanedNoSpace.slice(0, lastComma).replace(/,/g, "").replace(/\./g, ""); const afterDecimal = cleanedNoSpace.slice(lastComma + 1); cleanedNoSpace = beforeDecimal + "." + afterDecimal; } else if (lastDot > lastComma) { const beforeDecimal = cleanedNoSpace.slice(0, lastDot).replace(/\./g, "").replace(/,/g, ""); const afterDecimal = cleanedNoSpace.slice(lastDot + 1); cleanedNoSpace = beforeDecimal + "." + afterDecimal; } else if (lastComma !== -1) { cleanedNoSpace = cleanedNoSpace.replace(/,/g, ""); } else if (lastDot !== -1) { cleanedNoSpace = cleanedNoSpace.replace(/\./g, ""); } } } } const num = parseFloat(cleanedNoSpace) || 0; return isNegative ? -num : num; }; export { parseCurrencyString };