In this Oracle Apex tutorial, you will learn how to format a number with comma and decimal using JavaScript. In Oracle Apex, for a text field or a number field, there is a property Format Mask, in which you can specify the number format with comma and decimal for the currency fields, but it shows after the page load and usually we require it to show when user moves to the next field by pressing the Tab key or using the mouse. To achieve this functionality in Oracle Apex, we can use the JavaScript method Number(value).toFixed()
on the onfocusout
or onblur
event. Below are the examples:
Format Number with Comma and Decimal Using JavaScript Example
In the following example, we will use the JavaScript method Number(value).toFixed().replace()
on focusout
event to format the number into the currency format. Follow these steps:
Click on the Number Field in Oracle Apex page designer, for which you want to apply the format mask, then in the properties advance section paste the following JavaScript code in the Custom Attributes. Also, shown below in the image below:
onfocusout="this.value=Number(this.value).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')"
Now when the user will press the Tab key or will use the mouse to navigate to the next field, this field value will be formatted with commas and 2 decimal places. If you want to change it to show 4 decimal places then use toFixed(4)
.
JavaScript to Format a Number with 2 Decimal Places in Oracle Apex
To format a number with 2 decimal places without the comma, use the following JavaScript code in the Customer Attributes section:
onfocusout="this.value=Number(this.value).toFixed(2)"
Here in both examples, I used the onfocusout
JavaScript event, you can also use the onblur
JavaScript event for the same code. Below is the example:
onblur="this.value=Number(this.value).toFixed(2)"