开发者

Get first two digits of a string, support for negative 'numbers'

开发者 https://www.devze.com 2023-03-15 20:10 出处:网络
I have the following strings in JavaScript as examples: -77.230202 39.90234 -1.2352 I want to ge the first two digits, before the decimal.While maintaining the negative va开发者_如何学Clue.So the f

I have the following strings in JavaScript as examples:

-77.230202
39.90234
-1.2352

I want to ge the first two digits, before the decimal. While maintaining the negative va开发者_如何学Clue. So the first one would be '-77' and the last would be '-1'

Any help would be awesome!

Thank you.


You can simply use parseInt().

var num = parseInt('-77.230202', 10);
alert(num);

See it in action - http://jsfiddle.net/ss3d3/1/

Note: parseInt() can return NaN, so you may want to add code to check the return value.


Late answer, but you could always use the double bitwise NOT ~~ trick:

~~'-77.230202'  // -77
~~'77.230202'   // 77

~~'-77.990202'  // -77
~~'77.930202'   // 77

No octal concerts with this method either.


try this, but you'd have to convert your number to a string.:

var reg = /^-?\d{2}/,
num = -77.49494;

console.log(num.toString().match(reg))

["-77"]


var num = -77.230202;
var integer = num < 0 ? Math.ceil(num) : Math.floor(num);

Also see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math.


Do you just want to return everything to the left of the decimal point? If so, and if these are strings as you say, you can use split:

var mystring = -77.230202;
var nodecimals = mystring.split(".", 1);
0

精彩评论

暂无评论...
验证码 换一张
取 消