Reputation: 936
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
Upvotes: 0
Views: 60
Reputation: 173
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))
Upvotes: 2
Reputation: 761
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))
Upvotes: 1