使用 JavaScript 获取数字的小数部分 [英] Get decimal portion of a number with JavaScript

查看:18
本文介绍了使用 JavaScript 获取数字的小数部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有像 3.21.6 这样的浮点数.

I have float numbers like 3.2 and 1.6.

我需要将数字分成整数和小数部分.例如,3.2 的值将被拆分为两个数字,即 30.2

I need to separate the number into the integer and decimal part. For example, a value of 3.2 would be split into two numbers, i.e. 3 and 0.2

获取整数部分很容易:

n = Math.floor(n);

但我无法获取小数部分.我试过这个:

But I am having trouble getting the decimal portion. I have tried this:

remainder = n % 2; //obtem a parte decimal do rating

但它并不总是正常工作.

But it does not always work correctly.

前面的代码有如下输出:

The previous code has the following output:

n = 3.1 // gives remainder = 1.1

我在这里缺少什么?

推荐答案

使用1,而不是2.

js> 2.3 % 1
0.2999999999999998

这篇关于使用 JavaScript 获取数字的小数部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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