I need to format a number for a project im working on at work, only problem is that I cant format it how i want.
I convert the number to a localestring using the toLocaleString
method which gives me the commas but i also need decimal places, nothing i seem to do works.
var number = 123.322 number = parseFloat(number).toFixed(2) //123.22 number.toLocaleString() //123.22
The above code just returns the parsefloated number along with the tofixed decimal values but it doesn't add the commas.
How do i get a number to have two decimal places (when the value is 'xx.00') and also be comma separated. Is this possible in JavaScript?
toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.
The toLocaleString() method returns a string with a language-sensitive representation of this date. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .
Note. The toFixed() method will round the resulting value if necessary. The toFixed() method will pad the resulting value with 0's if there are not enough decimal places in the original number. The toFixed() method does not change the value of the original number.
In JavaScript, toLocaleString() is a Number method that is used to convert a number into a locale-specific numeric representation of the number (rounding the result where necessary) and return its value as a string.
You can give an object to .toLocaleString()
which describes what you want:
var sNumber = (10123.322).toLocaleString(undefined, {'minimumFractionDigits':2,'maximumFractionDigits':2});
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Original:
const fNumber = 10123.322; const sNumber = parseFloat(fNumber.toFixed(2)).toLocaleString(); console.log(sNumber);
The number is already in decimal/float format on the first line.
.toFixed(2)
turns it into a string using fixed-point notation.parseFloat()
takes that string and turns it back into a float..toLocaleString()
turns it into a string using the local format.Just to do it in one line
var num = '12233.3366554'; num = parseFloat(parseFloat(num).toFixed(2)).toLocaleString('en-IN', { useGrouping: true });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With