How to use a intl.NumberFormat In JavaScript
You can use the Intl.NumberFormat object for number formatting. Here’s how you can integrate it:
- In the HTML design, we used the main tag <canvas> to show the line graph. The element serves as the container for the pie chart visualization.
- It includes the Chart.js library through a CDN.
Syntax:
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
Example: The below code uses intl.NumberFormat() method to format the labels of Y-axis.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title > Formatted Y-axis Labels </ title > < script src = "https://cdn.jsdelivr.net/npm/chart.js" > </ script > </ head > < style > div { height: 400px; width: 400px; } </ style > < body > < h1 > w3wiki | </ h1 > < p > < b > format the labels of the Y axis in a chart? </ b > </ p > < div > < canvas id = "myChart" width = "400" height = "400" > </ canvas > </ div > < script > const ctx = document.getElementById('myChart'). getContext('2d'); const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); var myChart = new Chart(ctx, { type: 'line', data: { labels: ['January', 'February', 'March', 'April', 'May'], datasets: [{ label: 'Sales', data: [1000, 1500, 1200, 1800, 2000], backgroundColor: 'rgba(54, 162, 235, 0.5)', borderColor: 'rgba(54, 162, 235, 1)', borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { callback: function (value, index, values) { return formatter.format(value); } } }] } } }); </ script > </ body > </ html > |
Output:
How to Format the Labels of the Y Axis in a Chart ?
The y-axis in a chart is a basic aspect of data visualization that indicates the significance of data points and contributes to the overall visual appeal of the chat. Draw the chart using the chart.js JavaScript library. Formatting the y-axis also aids in conveying the meaning of data points.
Below are the approaches to set the Chart.js Y-axis title:
Table of Content
- Using a callback function
- Using a intl.NumberFormat
- Using a Custom Plugin