javascript jquery分隔十进制数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3574055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:33:57  来源:igfitidea点击:

Jquery separate decimal number

javascriptjquery

提问by Sergio

If I have decimal numbers like:

如果我有十进制数字,例如:

18.1234567

18.1234567

5.2345678

5.2345678

-77.7654321

-77.7654321

-0.4567891

-0.4567891

How can I separate number before and after decimal dot using Jquery and is there any function that can recognize negative value of the selected number?

如何使用 Jquery 在小数点前后分隔数字,是否有任何功能可以识别所选数字的负值?

回答by Tim Rogers

I'm assuming your numbers are held as decimals, not as strings? In which case, just use the math functions:

我假设你的数字是小数,而不是字符串?在这种情况下,只需使用数学函数:

Math.floor ( 18.1234567 ) // = 18
18.1234567 - Math.floor ( 18.1234567 ) // = .1234567

And checking for a negative number is just checking if it's < 0.

检查负数只是检查它是否 < 0。

回答by Haim Evgi

use javascript split function

使用javascript拆分功能

var str = '4.5';
var substr = str.split('.');
// substr[0] contains "4"
// substr[1] contains "5"

to see if this negative you can use javascript also :

看看这个否定你也可以使用javascript:

 nagative = str.indexOf("-");

if its return 1 (not zero) it is a negative number.

如果它返回 1(不是零),则它是一个负数。

回答by reko_t

You don't need jQuery for this at all:

你根本不需要jQuery:

var parts = num.toString().split('.');

If you want the values as integers instead of strings, you can just do parseInt(parts[0])to cast back to integer.

如果您希望将值作为整数而不是字符串,您可以parseInt(parts[0])将其转换回整数。