迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript获取小数点前的值

作者:迹忆客 最近更新:2022/12/21 浏览次数:

JavaScript获取小数点前的值:

  1. 将数字转换为字符串并使用 split() 方法将其按点拆分。
  2. split() 方法将返回一个数组,其中包含小数点前后的值。
  3. 访问索引 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

JavaScript获取小数点前的值

如果需要获取小数点后的部分,可以查看我的另一篇文章获取数字的小数部分。

我们创建了一个可重用的函数,它返回小数点前的值。

我们必须将数字转换为字符串,这样我们才能对其调用 String.split 方法。

split 方法将分隔符作为参数并将字符串拆分为子字符串数组。

console.log('23.45'.split('.')); // 👉️ ['23', '45']
console.log('0.34'.split('.')); // 👉️ ['0', '34']
console.log('7.7'.split('.')); // 👉️ ['7', '7']

最后一步是将字符串转换回数字并返回结果。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便