Customising the number to a currency format. See the below snippet. But when passing negative number i need to customise it.
function getMoneyValue(number) { var formatter = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }); return formatter.format(number) } console.log(getMoneyValue(200)) console.log(getMoneyValue(-200)) // expected [-] ₹200.00
So for customising referring Intl.NumberFormat When i tried this snippet the problem is i am not getting the rupee symbol
function getMoneyValue(number) { var formatter = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }); let parts = formatter.formatToParts(number).map((part) => { switch (part.type) { case "currency": return number >= 0? number: `[-] ${Math.abs(number)}`; default: return part.value; } }); return parts[1]; } console.log(getMoneyValue(200)) // expected ₹200.00 console.log(getMoneyValue(-200)) // expected [-] ₹200.00
Any help is appreciated, what is the better way to achieve this
function getMoneyValue(number) { var formatter = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }); if(number < 0) { return '[-] '+ formatter.format(Math.abs(number)) } return formatter.format(number) } console.log(getMoneyValue(200)) console.log(getMoneyValue(-200))
The check should have been against the type minusSign . You don't need to add a check under integer type as only integer type is passed without the -ve sign which be a positive integer value.
function getMoneyValue(number) { var formatter = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }); let parts = formatter.formatToParts(number).map(({type, value}) => { switch (type) { case "integer": return value; case "minusSign": return '[-]' default: return value; } }).reduce((string, part) => string + part); return parts; } console.log(getMoneyValue(200)) console.log(getMoneyValue(-200))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.