How to Convert Numbers to Strings in JavaScript: Complete Guide with Examples

目次

1. Introduction

JavaScript is a critically important programming language in web development. In particular, type conversion plays a key role in many scenarios, such as validating form input and formatting API responses.
In this article, we provide a detailed explanation of how to convert numbers to strings in JavaScript, covering everything from basic usage to advanced techniques.

By reading this article, even beginners will be able to understand how to convert numbers into strings and apply these techniques effectively in real-world development.

2. Basic Methods for Converting Numbers to Strings in JavaScript

JavaScript provides multiple ways to convert numbers into strings. In this section, we explain three of the most commonly used methods.

2.1 Using the String() Function

The simplest way to convert a number into a string is by using the built-in String() function.

Usage Example

let num = 123;
let str = String(num);
console.log(typeof str); // "string"

Explanation

  • By simply writing String(number), the numeric value is converted into a string.
  • The original number is not modified; instead, a new string value is returned.

Advantages and Considerations

  • The code is simple and highly readable.
  • The data type is explicitly guaranteed, reducing the likelihood of errors.
  • However, it does not support trimming whitespace or applying special formatting.

2.2 Using the toString() Method

The toString() method is a built-in method of JavaScript number objects and allows for more flexible conversions.

Usage Example

let num = 456;
let str = num.toString();
console.log(str); // "456"

Explanation

  • Since it is a method of the number object, it can be called directly on numeric values.
  • It also supports conversion to different numeral systems, such as binary or hexadecimal.

Example with Radix Specification

let num = 255;
let binaryStr = num.toString(2); // binary
console.log(binaryStr); // "11111111"

Advantages and Considerations

  • By specifying a radix, you can convert numbers into strings while changing the numeral system.
  • An error will occur if the value is undefined or null, so type checking is required in advance.

2.3 Using Template Literals

In modern JavaScript, template literals (backticks) provide a simple and intuitive way to convert numbers into strings.

Usage Example

let num = 789;
let str = `${num}`;
console.log(str); // "789"

Explanation

  • Template literals allow for intuitive string conversion.
  • They can easily be combined with other strings, enabling flexible formatting.

Advantages and Considerations

  • The syntax is simple and visually easy to understand.
  • Supports complex formatting, including expressions.
  • Template literals are supported from ES6 onward, so caution is required for older browsers.

3. Advanced Topics: Converting and Formatting Special Numeric Values

In this section, we explore advanced techniques for converting numbers to strings in JavaScript. In particular, handling decimal values and specifying output formats are frequently required in real-world development scenarios.

3.1 Handling Decimals and Format Specification

When converting numbers that include decimal points into strings, you can use methods that allow you to control the display format.

1. Using the toFixed() Method

The toFixed() method generates a string while specifying the number of digits after the decimal point.

Usage Example
let num = 123.456;
let str = num.toFixed(2);
console.log(str); // "123.46"

Explanation

  • The value is rounded to the number of decimal places specified as the argument.
  • The return value is a string, so no additional conversion is required.

Advantages and Considerations

  • Values may be rounded more than expected, so additional handling may be required when precision is critical.
  • If no argument is specified, the default is zero decimal places.

Practical Example: Currency Display

let price = 1234.5;
let formattedPrice = "$" + price.toFixed(2);
console.log(formattedPrice); // "$1234.50"

2. Using the toPrecision() Method

The toPrecision() method generates a string by specifying the total number of significant digits.

Usage Example
let num = 123.456;
let str = num.toPrecision(4);
console.log(str); // "123.5"

Explanation

  • By specifying the number of significant digits, rounding and formatting are applied simultaneously.

Advantages and Considerations

  • The result may be displayed in exponential notation, making it unsuitable when a fixed format is required.

3.2 Converting to Currency and Percentage Formats

When displaying data, it is often necessary to format values as currency or percentages.

1. Currency Formatting with Intl.NumberFormat

The Intl.NumberFormat object allows you to easily format numbers as currency.

Usage Example
let price = 1234567.89;
let formatted = new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(price);
console.log(formatted); // "¥1,234,568"

Explanation

  • By specifying the locale and currency code, the number is automatically formatted correctly.
  • Thousands separators are applied automatically, eliminating the need for manual processing.

Practical Example: Formatting as USD

let usdPrice = 1234.56;
let formattedUSD = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(usdPrice);
console.log(formattedUSD); // "$1,234.56"

2. Converting to Percentage Format

The following example demonstrates how to easily format numbers as percentages.

Usage Example
let rate = 0.1234;
let percent = new Intl.NumberFormat('en-US', { style: 'percent', minimumFractionDigits: 2 }).format(rate);
console.log(percent); // "12.34%"

Explanation

  • Decimal values are converted to percentage notation, with control over decimal places.

4. Important Considerations and Error Handling When Converting Numbers and Strings

Although JavaScript makes it easy to convert between numbers and strings, errors or unintended behavior can occur in certain cases. This section introduces key considerations and practical examples of error handling.

4.1 Detecting and Handling NaN (Not a Number)

In JavaScript, NaN (Not a Number) occurs when numeric operations or conversions fail. Let’s review how to detect and handle it properly.

1. Basic NaN Detection

Example: Generating NaN
let result = "abc" * 2; // Invalid operation
console.log(result); // NaN

As shown above, operations between strings and numbers are invalid, resulting in NaN.

Example: Using isNaN()
let value = "abc" * 2;
console.log(isNaN(value)); // true

2. Using Number.isNaN()

In ES6, Number.isNaN() was introduced for more precise detection.

Example: Strict Detection
console.log(isNaN("123"));          // false (due to type coercion)
console.log(Number.isNaN("123"));   // false (no type coercion)

Key Points

  • isNaN() performs type coercion, which can lead to unexpected results.
  • Number.isNaN() does not perform type coercion, making it more reliable.

4.2 Techniques to Prevent Type Conversion Errors

1. Safe Type Checking Example

To prevent unexpected errors caused by mixing numbers and strings, you can perform type checks in advance.

Example: Checking the Type Before Processing
let value = "123";

if (typeof value === "number") {
  console.log(value.toString());
} else if (!isNaN(value)) {
  console.log(String(Number(value)));
} else {
  console.log("Invalid input value");
}

Explanation

  • By checking the data type in advance and handling invalid values, overall safety is improved.

2. Setting Default Values

Setting default values is also an effective strategy when invalid input is provided.

Example: Applying a Default Value
function safeConvert(value) {
  return isNaN(value) ? "0" : String(value);
}

console.log(safeConvert("123")); // "123"
console.log(safeConvert("abc")); // "0"

Key Points

  • By using isNaN(), processing can continue safely with a default value when errors occur.

4.3 Handling Floating-Point Precision Errors

JavaScript floating-point calculations can produce precision errors. Let’s review how to mitigate them.

1. Example of a Precision Error

let result = 0.1 + 0.2;
console.log(result); // 0.30000000000000004

2. Methods to Eliminate Precision Errors

Method 1: Using toFixed()
let result = (0.1 + 0.2).toFixed(2);
console.log(result); // "0.30"
Method 2: Using Integer Arithmetic
let result = (0.1 * 10 + 0.2 * 10) / 10;
console.log(result); // 0.3

Key Points

  • Floating-point arithmetic can introduce errors, so countermeasures are necessary.
  • For financial calculations or precision-critical logic, integer arithmetic is recommended.

5. FAQ: Frequently Asked Questions and Troubleshooting

When converting numbers to strings in JavaScript, developers from beginners to intermediate levels often encounter various questions and issues. This section introduces common questions and their solutions.

5.1 How can I verify that a number has been converted into a string?

Question:
I want to confirm whether a number has been successfully converted into a string. Is there a simple way to check?

Answer:
You can verify the conversion by checking the data type of the result.

Example: Using the typeof Operator

let num = 123;
let str = String(num);
console.log(typeof str); // "string"

Key Points:

  • The typeof operator returns the type of a variable as a string.
  • To check whether a value is a number, use typeof num === “number”.

5.2 Why do errors occur when converting numbers?

Question:
An error occurred during code execution. What could be the cause?

Answer:
Errors may occur when the value being converted is undefined or null.

Example: Handling undefined and null Safely

let value = null;

// Convert safely
let str = value !== null && value !== undefined ? String(value) : "Default value";
console.log(str); // "Default value"

Key Points:

  • Checking for value existence in advance helps prevent errors.
  • Setting a default value improves the stability of your code.

5.3 Why does the converted string not match the expected format?

Question:
After converting a number to a string, the number of decimal places or format is not what I expected. What should I do?

Answer:
Use toFixed() or Intl.NumberFormat to explicitly specify the format.

Example 1: Fixing Decimal Places

let num = 123.456;
let str = num.toFixed(2);
console.log(str); // "123.46"

Example 2: Adding Thousand Separators or Currency Symbols

let price = 1234567.89;
let formatted = new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(price);
console.log(formatted); // "¥1,234,568"

Key Points:

  • Select the appropriate method to control numeric display formats.
  • International formatting should be considered when necessary.

5.4 How should I handle accidental conversion of non-numeric strings?

Question:
A string was mistakenly treated as a number, causing an error. How can I prevent incorrect conversions?

Answer:
Validate input data in advance and confirm that it is numeric before conversion.

Example: Combining Validation and Conversion

let input = "abc"; // User input

if (!isNaN(input)) {
  let str = String(Number(input));
  console.log(str);
} else {
  console.log("Invalid input value.");
}

Key Points:

  • Combining input validation with error handling helps prevent invalid data processing.
  • Extra caution is required when handling user input.

5.5 How can I maintain floating-point precision?

Question:
I want to resolve the issue where 0.1 + 0.2 results in 0.30000000000000004.

Answer:
Since floating-point arithmetic introduces precision errors, use integer arithmetic or fixed decimal formatting.

Example 1: Using Integer Arithmetic

let result = (0.1 * 10 + 0.2 * 10) / 10;
console.log(result); // 0.3

Example 2: Fixing Decimal Places

let result = (0.1 + 0.2).toFixed(2);
console.log(result); // "0.30"

Key Points:

  • Floating-point calculations can produce errors, so preventive measures are necessary.
  • Separating calculation data from display data improves safety and accuracy.

6. Summary and Related Resources

This article provided a comprehensive explanation of how to convert numbers to strings in JavaScript, covering basic methods, advanced techniques, important considerations, and FAQs. Let’s review the key takeaways.

6.1 Key Points Summary

1. Basic Conversion Methods

  • String() Function: Simple and beginner-friendly.
  • toString() Method: Flexible, supports radix and numeral system conversion.
  • Template Literals: Modern syntax offering clarity and ease of use.

2. Advanced Formatting and Display Control

  • toFixed(): Controls the number of decimal places.
  • Intl.NumberFormat: Simplifies currency and percentage formatting.

3. Error Handling and Best Practices

  • NaN Detection: Use isNaN() and Number.isNaN() to prevent errors.
  • Safe Type Conversion: Validate data types before processing.
  • Floating-Point Precision Handling: Use integer arithmetic or fixed decimal control.

4. FAQ-Based Troubleshooting

  • Practical solutions for input errors and formatting issues.
  • Real-world code examples to strengthen troubleshooting skills.

6.2 Practical Use Cases

The techniques introduced in this article can be applied in the following scenarios:

  • E-commerce Price Displays: Improve readability using currency formatting.
  • Data Visualization Tools: Format numeric values with units or percentages.
  • Form Input Validation: Validate and safely process user input.
  • Logging and Debugging: Convert numeric values to strings for clear output.

6.3 Related Links and References

For those who want to dive deeper or consult official documentation, the following resources are recommended:

6.4 Final Notes

Converting numbers to strings in JavaScript is a fundamental skill used throughout web applications.

Skills Gained from This Article:

  • Understanding basic type conversion techniques.
  • Formatting numeric data appropriately for different contexts.
  • Writing stable and error-resistant code.

Use these techniques to build practical and reliable web applications.

Additional Notes and Future Learning

To further improve your JavaScript skills, consider learning reverse conversions from strings to numbers and more advanced data type manipulation techniques. These topics will be covered in future articles—stay tuned!

広告