Accounting currency calculation result always shown in two decimal digits or specific digits format. JavaScript doesn’t provide direct number formatting.
To rounding extra decimal or add extra decimal in number to be shown in output, we need make own code.
JavaScript provides a function of toFixed() passed with length value and it will return output as string number of specific length of decimal.
JavaScript number formatting has two functions
- Number.toFixed(x) x= length of decimal digits.
- Number.toPrecision(x) x=total length of number
1. toFixed() is used to fixed digits of decimal number. X is denoted as number of decimal digit to display in output. Extra digit it can round off and if fewer digits in number found, it will add extra decimal digits.
e.g
var number=1234567;
number.toFixed(2);
output : 1234567.00
var number=1234567.12345;
number.toFixed(2);
output : 1234567.12
2. number.toPrecision() is used to make total digits of number. Let take an example
var number=1234567;
number.toPrecision(4);
output : 1234
Demo
<html> <head> <title>JavaScript-Number Formatting</title> <script> function toFormatNumberFix() { var number=parseFloat(document.frm.digitrnd.value); var finaloutput = number.toFixed(2); alert(finaloutput) } function toFormatNumberRound() { var number=parseFloat(document.frm.rnddecimal.value); var finaloutput = number.toPrecision(3); alert(finaloutput) } </script> </head> <body> <form name="frm"> <input type="text" name="digitrnd"> <input type="button" value="Go" name="goto" onClick="toFormatNumberFix()"> For toFixed number<br> <input type="text" name="rnddecimal"> <input type="button" value="Go" name="goo" onClick="toFormatNumberRound()"> For toPrecision number<br> </form> </body> </html>




Link to Us