在 Javascript 中,小数点后只有双零的数字在转换为 String 时丢失了双零?为什么?
In Javascript numbers with only double zeros in their decimal place lost their double zero when converted to String ? Why?
我正在开发一个 Web 应用程序,我需要在其中将一些数字连接为字符串格式
其中一个数字如果是整数(例如15.00),小数点后需要00
但是当我将它与其他数字连接时,00 丢失了(例如 15.00 => 15)
一个例子:
const price = 15.00;
const period = 3;
const CC = 840;
const concated = `${price}${period}${CC}`;
console.log(concated);
const saltedHash = crypto.createHash('md5').update(`${concated}GhVT+6FySEgWVeUWCHLo2lks`).digest('hex');
post[0].saltedHash = saltedHash;
post[0].string = `${concated}GhVT+6FySEgWVeUWCHLo2lks`;
现在的问题是,常量 concated
包含 153840
而不是 15.003840
为什么会出现这个问题?
如何保留00?
您可以使用 toFixed()
来实现,例如:
const concated = `${price.toFixed(2)}${period}${CC}`;
const price = 15.00;
const period = 3;
const CC = 840;
const concated = `${price.toFixed(2)}${period}${CC}`;
console.log(concated);
问题是,当您使用 template literal 时,它会将数字转换为字符串,即 String(15) === "15"
,而当您使用 15..toFixed(2)
时,它会 "returns a string representing a number in fixed-point notation".
因此,15..toFixed(2) === "15.00"
,即typeof 15.00.toFixed(2) === "string"
我正在开发一个 Web 应用程序,我需要在其中将一些数字连接为字符串格式
其中一个数字如果是整数(例如15.00),小数点后需要00
但是当我将它与其他数字连接时,00 丢失了(例如 15.00 => 15)
一个例子:
const price = 15.00;
const period = 3;
const CC = 840;
const concated = `${price}${period}${CC}`;
console.log(concated);
const saltedHash = crypto.createHash('md5').update(`${concated}GhVT+6FySEgWVeUWCHLo2lks`).digest('hex');
post[0].saltedHash = saltedHash;
post[0].string = `${concated}GhVT+6FySEgWVeUWCHLo2lks`;
现在的问题是,常量 concated
包含 153840
而不是 15.003840
为什么会出现这个问题?
如何保留00?
您可以使用 toFixed()
来实现,例如:
const concated = `${price.toFixed(2)}${period}${CC}`;
const price = 15.00;
const period = 3;
const CC = 840;
const concated = `${price.toFixed(2)}${period}${CC}`;
console.log(concated);
问题是,当您使用 template literal 时,它会将数字转换为字符串,即 String(15) === "15"
,而当您使用 15..toFixed(2)
时,它会 "returns a string representing a number in fixed-point notation".
因此,15..toFixed(2) === "15.00"
,即typeof 15.00.toFixed(2) === "string"