0

I am using http://numeraljs.com/#format

I need formatter, which can covert number with apostrophe to comma.

Eg: 2'910'724'242 must change to 2,910,724,242

Is there any formatter available. Or we have to manually convert apostrophe to comma.

Mike Phils
  • 3,475
  • 5
  • 24
  • 45
  • This can easily be done using string.replace but if you want lib's function, would request you to show how you are using it – Rajesh Sep 06 '22 at 10:51

2 Answers2

0

No need for a library

let str = `2'910'724'242`

let num = (+str.replaceAll("'","")).toLocaleString('en-US'); // replace(/'/g,"") is an alternative to the replaceAll

console.log(num)

str = `2'910'724'242.019999999`

num = (+str.replaceAll("'","")).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2});

console.log(num)

But if you insist

let str = `2'910'724'242`

console.log(
  numeral(+str.replaceAll("'","")).format('0,0')
)  

str = `2'910'724'242.0199999`

console.log(
  numeral(+str.replaceAll("'","")).format('0,0.00')
)  
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/1.0.3/numeral.min.js" ></script>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • I meant that only. Was going to say i english but then thought to write in JS and got confused. But objective of my comment was to know if using `toLocaleString` gives some advantage – Rajesh Sep 06 '22 at 10:56
  • User wanted thousand separator commas. If you do not use toLocaleString, you will get `2910724242` – mplungjan Sep 06 '22 at 11:03
0

It may not be the best way (I'm not familiar with the library) but, since you can't seemingly set the format on parsing, you can change the default:

let input = "2'910'724'242.6666";
numeral.defaultFormat("0'0.00");
let number = numeral(input);
let output = number.format("0,0.00");
console.log("Input: %s; Output: %s", input, output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
Álvaro González
  • 142,137
  • 41
  • 261
  • 360