JavaScript String():将数字转换为字符串

用 String(value) 将数字转换为文本。String(1200) 返回 '1200',原来的数字保持不变。需要千位分隔符或固定小数位数时,请使用数字格式化功能。

String() 的返回值与类型

用 typeof 检查结果是否为 'string'。无参数的 String() 返回空字符串。传入 null 或 undefined 会得到对应的文字。普通转换无需 new。new String(0) 创建包装 '0' 的对象,与基本类型的 '0' 严格比较时不相等。

调用 结果 类型
String(1200) "1200" string
String(0) "0" string
String(false) "false" string
String(null) "null" string
String(undefined) "undefined" string
String() "" string
new String(0) "0" object

MDN String() 参考文档

区分加法、拼接与显示格式

12 加 3 等于 15。若先将两者转成文本,再用 + 拼接,结果是 '123'。先相加再转换则得到 '15'。需要把字符串用于计算时,请先检查它是否符合预期的数字格式。

const a = 12;
const b = 3;
console.log(a + b);                  // 15
console.log(String(a) + String(b));  // "123"
console.log(String(a + b));          // "15"
console.log(String(1000.00));        // "1000"
console.log(String(Number('0012'))); // "12"
console.log(String(1e21));           // "1e+21"
console.log((1.2).toFixed(2));       // "1.20"
const format = new Intl.NumberFormat('de-DE');
console.log(format.format(1234.5));  // "1.234,5"

String(1000.00) 得到 '1000',String(Number('0012')) 得到 '12'。数字化时丢失的零无法通过转换找回。标识符应该从一开始就保存为字符串。用 toFixed(2) 显示两位小数,或用 Intl.NumberFormat 应用地区分隔符。

ECMAScript 数字转换与显示规范

在浏览器选择一个值进行转换

将示例用 UTF-8 保存为 string-conversion.html 后打开。下拉列表保存键,Map 提供实际值。初始结果为 number、'1200' 和 string。也可以试试 null 和 Symbol('id')。JSON.stringify() 让引号可见,textContent 将结果作为文本显示。

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport"
        content="width=device-width, initial-scale=1">
  <title>将值转换为字符串</title>
</head>
<body>
  <label for="sample">要转换的值</label>
  <select id="sample">
    <option value="number">1200</option>
    <option value="zero">0</option>
    <option value="boolean">false</option>
    <option value="null">null</option>
    <option value="undefined">undefined</option>
    <option value="bigint">42n</option>
    <option value="symbol">Symbol('id')</option>
  </select>
  <button id="convert" type="button">转换</button>
  <pre id="output" aria-live="polite"></pre>
  <script>
    const values = new Map([
      ['number', 1200], ['zero', 0], ['boolean', false],
      ['null', null], ['undefined', undefined],
      ['bigint', 42n], ['symbol', Symbol('id')],
    ]);
    const sample = document.querySelector('#sample');
    const output = document.querySelector('#output');

    function convert() {
      const value = values.get(sample.value);
      const text = String(value);
      output.textContent = [
        "原始类型:" + typeof value,
        "字符串表示:" + JSON.stringify(text),
        "转换后的类型:" + typeof text,
      ].join('\n');
    }

    document.querySelector('#convert').addEventListener('click', convert);
    convert();
  </script>
</body>
</html>

处理缺失值和 Symbol

用 String(value ?? '') 将缺失值显示为空字符串。?? 只替换 null 和 undefined,因此会保留 0 和 false。显式调用 String(Symbol('id')) 返回 'Symbol(id)'。在模板字面量中直接插入 Symbol 会抛出 TypeError。要传输对象结构,请选择 JSON 等格式并验证其序列化规则。

const display = value => String(value ?? '');
console.log(JSON.stringify(display(null))); // '""'
console.log(display(0));                     // "0"
console.log(display(false));                 // "false"
console.log(String(Symbol('id')));           // "Symbol(id)"