在 Javascript 中将 int 12345 转换为 float 1.2345
Turn int 12345 into float 1.2345 in Javascript
我想把 12345 变成 1.2345
这与不同的数字。
这是我到目前为止所做的,并且有效,只是不是很漂亮,而且看起来像是 hack。
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()
只接受一个参数(指数)并将其应用于欧拉常数。 Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.
除以 10000
无效,因为数字并不总是 12345
。它可能是 123
或 1234234614
。在这两种情况下,我仍然需要 1.23
或 1.234234614
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;
}
function f(n){
return n/(Math.pow(10, Math.floor(Math.log10(n))));
}
您需要将 n 除以 10^x,其中 x 是 "long" 数字的大小。原来这个数的长度就是这个数的对数的底
我想把 12345 变成 1.2345
这与不同的数字。
这是我到目前为止所做的,并且有效,只是不是很漂亮,而且看起来像是 hack。
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()
只接受一个参数(指数)并将其应用于欧拉常数。 Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.
除以 10000
无效,因为数字并不总是 12345
。它可能是 123
或 1234234614
。在这两种情况下,我仍然需要 1.23
或 1.234234614
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;
}
function f(n){
return n/(Math.pow(10, Math.floor(Math.log10(n))));
}
您需要将 n 除以 10^x,其中 x 是 "long" 数字的大小。原来这个数的长度就是这个数的对数的底