javascript 将字符串中的负数转换为javascript中的负十进制数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26551787/
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
convert negetive number in string to negative decimal in javascript
提问by Jayaraj PS
I have a string : "-10.456"; I want to convert it to -10.465 in decimal (using Javascript) so that i can comapare for greater than or lesser than with another decimal number.
我有一个字符串:“-10.456”;我想将它转换为十进制的 -10.465(使用 Javascript),这样我就可以比另一个十进制数大或小。
Regards.
问候。
回答by Grice
The parseIntfunction can be used to parse strings to integers and uses this format: parseInt(string, radix);
该parseInt函数功能,可以用来解析字符串为整数,并采用以下格式:parseInt(string, radix);
Ex: parseInt("-10.465", 10);
returns -10
例如:parseInt("-10.465", 10);
退货-10
To parse floating point numbers, you use parseFloat, formatted like parseFloat(string)
要解析浮点数,请使用parseFloat,格式如下parseFloat(string)
Ex: parseFloat("-10.465");
returns -10.465
例如:parseFloat("-10.465");
退货-10.465
回答by Drazzah
Here are two simple ways to do this if the variable str = "-10.123":
如果变量 str = "-10.123",这里有两种简单的方法可以做到这一点:
#1
#1
str = str*1;
str = str*1;
#2
#2
str = Number(str);
str = Number(str);
Both ways now contain a JavaScript number primitive now. Hope this helps!
两种方式现在都包含一个 JavaScript 数字原语。希望这可以帮助!
回答by jrahhali
In javascript, you can compare mixed types. So, this works:
在 javascript 中,您可以比较混合类型。所以,这有效:
var x = "-10.456";
var y = 5.5;
alert(x < y) // true
alert(x > y) // false
回答by Muhammad Umer
the shortcut is this:
捷径是这样的:
"-3.30" <--- the number in string form
+"-3.30" <----Add plus sign
-3.3 <----- Number in number type.