简体   繁体   English

在javascript中获取小数点后的值

[英]get the value after decimal point in javascript

I have a javascript number 12.1542. 我有一个JavaScript编号12.1542。 and I want the new string 12.(1542*60) from this string. 我想要这个字符串中的新字符串12.(1542 * 60)。

How can I get it. 我怎么才能得到它。 Thanks 谢谢

You could use the modulus operator : 您可以使用模运算符

var num = 12.1542;
console.log(num % 1);

However, due to the nature of floating point numbers, you will get a number that is very slightly different. 但是,由于浮点数的性质,您将获得一个略有不同的数字。 For the above example, Chrome gives me 0.15419999999999945 . 对于上述示例,Chrome给了我0.15419999999999945

Another (slightly longer) option would be to use Math.floor and then subtract the result from the original number: 另一个(稍微长一点)的选项是使用Math.floor ,然后从原始数字中减去结果:

var num = 12.1542;
console.log(num - Math.floor(num));​

Again, due to the nature of floating point numbers you will end up with a number that is very slightly different than you may expect. 同样,由于浮点数的性质,您最终得到的数字将与您预期的稍有不同。

floor is probably the method to get what you want: floor可能是获得所需内容的方法:

http://www.w3schools.com/jsref/jsref_floor.asp http://www.w3schools.com/jsref/jsref_floor.asp

You could also use ceil 您也可以使用ceil

http://www.w3schools.com/jsref/jsref_obj_math.asp http://www.w3schools.com/jsref/jsref_obj_math.asp

Input sanity checks aside, this should work: 除了输入健全性检查,这应该工作:

var str = '12.1542';
var value = Math.floor( str ) + ( 60 * (str - Math.floor( str ) ) );

Time to decimals: 小数时间:

function toDec(sec){
    var itg=Math.floor(sec);
    sec=(sec-itg)*60;
    return itg+sec; // OR: return new String(itg+sec);
}
let Decimal = "12.56"

Decimal.substring(Decimal.indexOf(".")+1, Decimal .length)

// answer is 56.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM