Ever wanted to format your text like a boss in JavaScript? You’ve probably come across printf in C or Python and thought, “Why can’t I do this in JS?” Good news – you can! Let’s dive into how to use JavaScript printf-style formatting to make your life easier and your console logs prettier.
TL;DR
JavaScript doesn’t have a built-in printf, but you can mimic it using templates or libraries. It’s great for controlling how numbers, strings, and dates look. You can use formatting placeholders just like in C or Python. Tools like sprintf-js make it super simple!
What is printf anyway?
In other languages like C or Python, printf means “print formatted.” It lets you insert values into a string in a controlled way—like rounding numbers, aligning text, or padding strings with spaces. It looks like this:
printf("Hello %s, you have %d new messages", name, count)
The crazy-looking codes like %s and %d are called placeholders. Each one stands for a data type:
- %s – String
- %d – Integer
- %f – Floating (decimal) point number
- %% – A literal percent sign
Why JavaScript doesn’t have printf (but kind of does)
Out of the box, JavaScript doesn’t have printf. But the console.log function supports some basic formatting:
console.log("I have %d apples and %s oranges", 5, "two")
This will output: I have 5 apples and two oranges
That’s cool, right? But don’t expect full-blown printf behavior. For anything fancy, we’ll need a little help!
Enter sprintf-js: The printf Hero JS Deserves
If you want true printf-style power in JavaScript, use a library like sprintf-js. It gives you full control to format strings like a pro.
First, install it:
npm install sprintf-js
Then use it like so:
const sprintf = require("sprintf-js").sprintf;
console.log(sprintf("You scored %.2f out of %d", 93.4567, 100));
This outputs: You scored 93.46 out of 100 (see how it rounds to 2 decimal places?)
Common printf-style Formats
With sprintf-js, you can do a lot! Here are some formatting codes you’ll start loving:
- %s – Insert a string
- %d – Insert an integer
- %.2f – Insert float with 2 decimal places
- %03d – Pad a number with zeroes (e.g., 005)
- %-10s – Left-align a string in 10 characters
- %10s – Right-align a string in 10 characters
Real-World Examples
Let’s look at some ways you can use printf-style formatting in the real world.
1. Showing prices with currency
const sprintf = require("sprintf-js").sprintf;
let price = 25.5;
console.log(sprintf("Total: $%.2f", price));
Output: Total: $25.50
2. Padding invoice numbers
console.log(sprintf("Invoice #%06d", 123));
Output: Invoice #000123
3. Tables and alignment
console.log(sprintf("%-10s | %10s", "Item", "Price"));
console.log(sprintf("%-10s | $%9.2f", "Apple", 0.6));
console.log(sprintf("%-10s | $%9.2f", "Banana", 0.75));
Output:
Item | Price Apple | $ 0.60 Banana | $ 0.75
Now your output isn’t just readable, it’s beautiful!
Now go forth, format fearlessly, and impress your coworkers with beautifully aligned console magic.