Number to String JavaScript: Converting Numbers to Text
A practical guide to converting numbers to strings in JavaScript, covering toString(), String(), template literals, padding, edge cases, and locale formatting with real code examples.

According to JavaScripting, converting numbers to strings in JavaScript is a common task you’ll encounter when rendering UI, logging data, or serializing values. The primary methods are toString(), String(), and template literals, each with its own nuance. This quick answer outlines when to use each approach and highlights key edge cases like NaN or undefined before you dive into full examples.
Introduction: Why the keyword number to string javascript matters
Numbers and strings are distinct primitive types in JavaScript, but you’ll frequently need to present numeric data as text. This is essential for UI rendering, building IDs, or preparing values for JSON and logs. The JavaScript language provides multiple, reliably consistent ways to convert numbers to strings. According to JavaScripting, understanding these patterns helps you write robust, readable code and reduces runtime surprises when formatting data for displays or APIs. In this section, you’ll see the core conversion concepts and why choosing the right approach matters for correctness and performance.
const n = 42;
const s = n.toString();
console.log(s); // "42"const x = 7;
const s2 = '' + x; // implicit conversion via concatenation
console.log(s2); // "7"Why it matters for performance and readability: explicit conversions (toString/String) are clearer to readers and often safer than implicit concatenation, especially in larger codebases.
Using toString(): direct, radix-aware conversion
The toString() method on numbers converts the value to a string. You can also specify a radix to render the number in binary, octal, or hexadecimal. This is particularly handy for debugging, encoding IDs, or formatting numbers for display in different bases.
(123).toString(); // "123"
(123).toString(10); // "123" (base 10)
(10).toString(2); // "1010" (binary)Notes:
- If you pass a non-number, toString() will still work on number-like values but may throw if called on undefined/null.
- Radix ranges from 2 to 36; common bases are 2 (binary) and 16 (hex).
Using String(): a general purpose converter
The String() function converts any value to its string representation, using a broad but predictable rule set. It’s a good choice when the value might not be a number yet you still want a string form for logging, UI, or serialization.
String(123); // "123"
String("123"); // "123"
String(undefined); // "undefined"
String(null); // "null"When to use String():
- When the input type is uncertain and you want a consistent string result
- When you want to avoid TypeError that can occur with direct method calls on undefined values
Template literals: concise conversion with formatting
Template literals offer a concise way to convert numbers to strings while enabling embedded expressions and straightforward formatting.
const n = 42;
`${n}`; // "42"
const price = 9.5;
`$${price.toFixed(2)}`; // "$9.50"Why use templates:
- They combine string construction with conversion in one step
- They’re resilient to different input types without extra checks
Padding and formatting before conversion
Sometimes you need a fixed-width string, such as IDs or codes. Pad numbers after conversion (or before, if you prefer) to achieve consistent length.
const id = 5;
id.toString().padStart(3, '0'); // "005"
'{}' // placeholder to show syntax continuationconst order = 42;
order.toString().padStart(5, '0'); // "00042"Best practice: combine with formatting steps when you need alignment or lexical sorting stability in logs or reports.
Edge cases: NaN, undefined, and locale-aware formatting
Conversions can look quirky for non-numeric inputs. NaN, Infinity, undefined, and null each behave differently depending on the method used. Be mindful of how you handle these values to avoid surprising UI output.
String(undefined); // "undefined"
String(null); // "null"
(NaN).toString(); // "NaN"
(Infinity).toString(); // "Infinity"A safer pattern is to provide a guard or fallback:
const safeToString = (v) => (typeof v === 'number' ? v.toString() : String(v));
console.log(safeToString(NaN)); // "NaN"
console.log(safeToString(undefined)); // "undefined"This approach aligns with robust error handling and predictable UI rendering.
Localization and advanced formatting: locale-aware strings
For user-facing applications, formatting numbers for a locale can be more important than raw string form. You can still convert to string after applying locale-aware formatting for display.
const value = 1234.5;
value.toLocaleString('en-US', { maximumFractionDigits: 2 }); // "1,234.5"
// If you want a string after formatting:
const formatted = value.toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2 });
console.log(formatted); // "1,234.5"Tip: locale-aware methods format numbers for readability, then you can explicitly convert to string for storage or transport when needed.
Steps
Estimated time: 40-60 minutes
- 1
Identify the conversion need
Determine whether you just need a plain string or a formatted display. Decide between explicit conversion (toString/String) or a template literal for embedding values.
Tip: Clarify inputs to avoid implicit conversions that can be harder to debug. - 2
Choose a method
Pick toString() for radix basics, String() for general conversion, or template literals for formatting.
Tip: Prefer explicit methods over string concatenation for readability. - 3
Write working examples
Create small snippets to verify behavior with numbers, NaN, and null to understand outputs.
Tip: Comment expected vs actual results to avoid regressions. - 4
Handle edge cases
Add guards for undefined or non-numeric inputs if your app may receive them.
Tip: Use a safeToString helper to centralize logic. - 5
Format for display
If locale or padding is needed, apply Intl.NumberFormat or padStart after conversion.
Tip: Keep formatting concerns separate from core conversion logic. - 6
Test across environments
Run tests in Node and in browsers to ensure consistent results across runtimes.
Tip: Edge-case behavior can differ slightly between engines.
Prerequisites
Required
- Required
- Basic command-line knowledgeRequired
- Basic understanding of numbers and strings in JavaScriptRequired
Optional
- A code editor (e.g., VS Code)Optional
- Optional: a browser console or Node environment to run examplesOptional
Commands
| Action | Command |
|---|---|
| Run a one-liner in NodeQuick check for conversion behavior | node -e "console.log(String(42))" |
| Convert inside a filePlace conversion code in index.js | node index.js |
| Template literal conversionInline conversion with formatting | node -e "console.log(`${42}`)" |
Questions & Answers
What is the simplest way to convert a number to a string in JavaScript?
The simplest approaches are toString() on a number or String(number). Both produce a string representation of the numeric value. Template literals offer a concise alternative when you are combining formatting with conversion.
Use toString() or String() for straightforward conversion. Template literals work well when you’re mixing in other text.
Can I convert NaN to a string without errors?
Yes. String(NaN) returns 'NaN', and (NaN).toString() also returns 'NaN'. However, ensure you don’t call toString() on undefined or null directly, as that would throw a TypeError.
Yes, NaN becomes the text 'NaN' when you convert it to a string.
What is the difference between toString() and String()?
toString() is a method on Number objects that returns a string representation and can take a radix. String() is a global function that converts any value to a string. For numeric inputs, both yield the numeric string, but String() handles more input types uniformly.
toString is a method on numbers; String is a general function for any value.
How do I pad numbers when converting to strings?
Convert to string first, then use padStart to enforce a fixed width. For example, (5).toString().padStart(3, '0') yields '005'. This is useful for IDs and sort-friendly strings.
Pad numbers after converting to strings to ensure consistent width.
Do template literals affect performance?
Template literals are highly optimized in modern engines and generally perform well for most UI formatting tasks. For extremely hot paths, measure and compare with explicit concatenation or toString when necessary.
They’re fast enough for typical use, but you can measure if you’re in a critical bottleneck.
What to Remember
- Use toString() for explicit numeric conversion.
- String() handles broader inputs with predictable text results.
- Template literals offer concise conversion with embedded formatting.
- PadStart helps create fixed-width strings for IDs.
- Guard edge cases to prevent runtime errors