在Javascript中将int 12345转换为float 1.2345

Turn int 12345 into float 1.2345 in Javascript

本文关键字:float 2345 转换 12345 Javascript 中将 int      更新时间:2023-09-26

我想把12345变成1.2345

这有不同的数字。

这是我到目前为止所做的,它很有效,只是不太好看,看起来像是一个黑客。

var number = 12345
> 12345
var numLength = number.toString().length
> 5
var str = number +'e-' + (numLength - 1)
> "12345e-4"
var float = parseFloat(str)
> 1.2345

有什么东西刚好把我的小数点后4位吗?

我试过

Math.pow(number, -4)
> 4.3056192580926564e-17

它甚至连我需要的东西都没有。

Math.exp()只接受一个参数(指数)并将其应用于Eulers常数。Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.

除以10000是行不通的,因为数字并不总是只有12345。可能是CCD_ 5或CCD_。在这两种情况下,我仍然需要1.231.234234614

function f(n){
    return n/(Math.pow(10, Math.floor(Math.log10(n))));
}

你需要把n除以10^x,其中x是数字的"长度"。结果是,数字的长度只是数字对数的底。

function getBase10Mantissa(input) {
  // Make sure we're working with a number.
  var source = parseFloat(input);
  // Get an integer for the base-10 log for the source value (round down in case of 
  // negative result).
  var exponent = Math.floor(Math.log10(source));
  // Raise 10 to the power of exponent and divide the source value by that.
  var mantissa = source / Math.pow(10, exponent);
  // Return mantissa only (per request).
  return mantissa;
}