上篇博客了解了js的数据类型,参考: 数据类型,这篇博客继续了解js的数据类型转换。
1.将数字转换成字符串
①全局方法 String() 可以将数字转换为字符串。
该方法可用于任何类型的数字,字母,变量,表达式:
const a = 453
String(a) // 将变量 a 转换为字符串并返回
String(888) // 将数字 888 转换为字符串并返回
String(5/2) // 将数字表达式转换为字符串并返回
②toString()方法
const a = 456
a.toString() // 将变量 a 转换为字符串并返回
(888).toString() // 将数字 888 转换为字符串并返回
(5/2).toString() // 将数字表达式转换为字符串并返回
③toLocaleString()方法,使用特定的语言环境将数字格式化为字符串
let num1 = 1000000;
let text1 = num1.toLocaleString();//输出:1,000,000
// 使用特定于的语言环境将数字格式化为货币字符串
//人民币
let num2 = 1000000;
let text3 = num3.toLocaleString("zh-CN", {style:"currency", currency:"CNY"});//输出:¥1,000,000.00
// 美元
let num3 = 1000000;
let text3 = num4.toLocaleString("en-US", {style:"currency", currency:"USD"});//输出:$1,000,000.00
④toFixed(x),把数字转换为字符串,结果的小数点后有指定位数的数字。
let num1 = 100;
num1.toFixed(2); //输出100.00
let num2 = 20.56;
num2.toFixed(1); //输出20.6
2.将布尔值转换成字符串
①全局方法String()
String(false); //输出“false”
String(true); //输出“true”
②toString()
let x = true;
x.toString(); //输出“true”
3.将日期转换为字符串
①全局方法 String() 可以将日期对象转换为字符串。
String(new Date()); //输出:"Mon Aug 15 2022 14:28:27 GMT+0800 (中国标准时间)"
②toString()
(new Date()).toString(); // 输出:"Mon Aug 15 2022 14:34:37 GMT+0800 (中国标准时间)"
③Date()方法,返回字符串
Date(); //输出:"Mon Aug 15 2022 14:28:27 GMT+0800 (中国标准时间)"
4.将字符串转换位数字
①全局方法 Number()
Number("77.66") // 返回 3.14
Number(" ") // 返回 0
Number("") // 返回 0
Number("5 7 8") // 返回 NaN
Number("aad") // 返回 NaN
②parseFloat() 与 parseInt()
//解析一个字符串,并返回一个浮点数。
parseFloat("56.77"); //输出:56.77
//解析一个字符串,并返回一个整数。
parseInt("56.78"); //输出:56
5.将布尔值转换位数字
Number(false) // 返回 0
Number(true) // 返回 1
6.将日期转换为数字
①全局方法 Number()
d = new Date();
Number(d) // 返回 1660547259250
②日期方法 getTime() 。
d = new Date();
d.getTime() // 返回 1660547259250