JavaScript获取小数点前的值
JavaScript获取小数点前的值:
-
将数字转换为字符串并使用
split()
方法将其按点拆分。 -
split()
方法将返回一个数组,其中包含小数点前后的值。 - 访问索引 0 处的数组元素并将其转换回数字。
function getValueBeforeDecimal(num) {
const beforeDecimalStr = num.toString().split('.')[0];
return Number(beforeDecimalStr);
}
console.log(getValueBeforeDecimal(123.456)); // 👉️ 123
console.log(getValueBeforeDecimal(1)); // 👉️ 1
console.log(getValueBeforeDecimal(-7.347)); // 👉️ -7
console.log(getValueBeforeDecimal(0.75)); // 👉️ 0
如果需要获取小数点后的部分,可以查看我的另一篇文章获取数字的小数部分。
我们创建了一个可重用的函数,它返回小数点前的值。
我们必须将数字转换为字符串,这样我们才能对其调用 String.split
方法。
split
方法将分隔符作为参数并将字符串拆分为子字符串数组。
console.log('23.45'.split('.')); // 👉️ ['23', '45']
console.log('0.34'.split('.')); // 👉️ ['0', '34']
console.log('7.7'.split('.')); // 👉️ ['7', '7']
最后一步是将字符串转换回数字并返回结果。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。