Home >Web Front-end >JS Tutorial >What are the JavaScript Alternatives to `printf` or `String.Format` for Number Formatting?
JavaScript Alternatives to printf/String.Format for Number Formatting
As a developer seeking a method to format numbers with thousand separators in JavaScript, you may be wondering if there's an equivalent to C/PHP's printf() or .NET's String.Format(). While the Microsoft Ajax library offers a version of String.Format(), it comes with significant overhead.
Fortunately, JavaScript now provides several options for such formatting.
ES6 Template Strings
Starting with ES6, JavaScript introduced template strings, which simplify string interpolation. Using template literals, you can write code like:
let soMany = 10; console.log(`This is ${soMany} times easier!`); // Output: "This is 10 times easier!"
sprintf.js Library
For older versions of JavaScript, the sprintf.js library is recommended. Install it via npm and use it as follows:
var sprintf = require("sprintf-js").sprintf; var formattedNumber = sprintf("%.2f", 1000000); // Output: "1,000,000.00"
Simultaneous Replacements
Alternatively, you can implement a simultaneous replacement function to handle format sequences like {0}{1}:
String.prototype.format = function() { var args = arguments; return this.replace(/\{([0-9]+)\}/g, function(match, index) { return args[index]; }); }; var formattedString = "{0}{1}".format("{1}", "{0}"); // Output: "{1}{0}"
The above is the detailed content of What are the JavaScript Alternatives to `printf` or `String.Format` for Number Formatting?. For more information, please follow other related articles on the PHP Chinese website!