Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức Number.toExponential() trong JavaScript là gì?

Number.toExponential() trả về chuỗi biểu diễn số dưới dạng ký hiệu khoa học (exponential notation).

Cú pháp

number.toExponential(fractionDigits?)
  • fractionDigits (tùy chọn): Số chữ số sau dấu phẩy (0-20). Mặc định: cần thiết để biểu diễn số.

Ví dụ

<!DOCTYPE html>
<html>
<body>
    <script>
        var num = 77.1234;
        
        document.write("toExponential(): " + num.toExponential() + "<br>");
        // "7.71234e+1" (mặc định đủ chữ số)
        
        document.write("toExponential(4): " + num.toExponential(4) + "<br>");
        // "7.7123e+1" (4 chữ số sau dấu phẩy)
        
        document.write("toExponential(2): " + num.toExponential(2) + "<br>");
        // "7.71e+1"
        
        // Gọi trực tiếp trên literal (cần dấu chấm kép hoặc ngoặc)
        document.write("77.1234.toExponential(): " + 77.1234.toExponential() + "<br>");
        document.write("(77).toExponential(): " + (77).toExponential() + "<br>");
    </script>
</body>
</html>

Định dạng kết quả:

[sign]digit.[fractionDigits]e[sign]exponent
VD: 7.7123e+1 = 7.7123 × 10^1 = 77.123

Lưu ý:

  • Trả về String, không phải Number.
  • Làm tròn (round) chứ không cắt (truncate).
  • Gọi trên number literal: 77..toExponential() (2 dấu chấm) hoặc (77).toExponential().
  • Dùng cho hiển thị số rất lớn/nhỏ (khoa học, kỹ thuật).

Phương thức liên quan:

  • toFixed(d) — Định dạng cố định chữ số thập phân (VD: "77.12").
  • toPrecision(p) — Tổng số chữ số có nghĩa (VD: "77.1").