dzm
dzm

Reputation: 23554

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

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 value. So the first one would be '-77' and the last would be '-1'

Any help would be awesome!

Thank you.

Upvotes: 0

Views: 2885

Answers (5)

user113716
user113716

Reputation: 322512

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.

Upvotes: 1

JohnK813
JohnK813

Reputation: 1124

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);

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 73011

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.

Upvotes: 4

Tomalak
Tomalak

Reputation: 338278

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.

Upvotes: 0

hellatan
hellatan

Reputation: 3577

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"]

Upvotes: 0

Related Questions