如何获取Javascript中浮点数的小数位? [英] How do I get the decimal places of a floating point number in Javascript?

查看:75
本文介绍了如何获取Javascript中浮点数的小数位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要拥有的是与Number.prototype.toPrecision()几乎相反的东西,这意味着当我拥有数字时,它拥有多少个小数?例如

What I would like to have is the almost opposite of Number.prototype.toPrecision(), meaning that when i have number, how many decimals does it have? E.g.

(12.3456).getDecimals() // 4

推荐答案

对于想知道如何更快地执行此操作(不转换为字符串)的人,以下是一种解决方案:

For anyone wondering how to do this faster (without converting to string), here's a solution:

function precision(a) {
  var e = 1;
  while (Math.round(a * e) / e !== a) e *= 10;
  return Math.log(e) / Math.LN10;
}

涵盖边缘情况的更完整解决方案:

a more complete solution with edge cases covered:

function precision(a) {
  if (!isFinite(a)) return 0;
  var e = 1, p = 0;
  while (Math.round(a * e) / e !== a) { e *= 10; p++; }
  return p;
}

这篇关于如何获取Javascript中浮点数的小数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆