最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rounding - Javascript - Remove leading zero from string - Stack Overflow

programmeradmin4浏览0评论

This is probably a super easy one. But I've got a series of numbers which looks like this:

0.12704174228675136
0.3629764065335753

I want to remove the leading 0. and keep only the two first numbers, so this is the result:

12
36

But I don't know how to round numbers . Usually, I'd convert it to a string and use regular expression. I guess I could do that now as well, but since I've got numbers here, I mind as well learn this now.

This is probably a super easy one. But I've got a series of numbers which looks like this:

0.12704174228675136
0.3629764065335753

I want to remove the leading 0. and keep only the two first numbers, so this is the result:

12
36

But I don't know how to round numbers . Usually, I'd convert it to a string and use regular expression. I guess I could do that now as well, but since I've got numbers here, I mind as well learn this now.

Share edited Jul 2, 2014 at 22:00 user229044 240k41 gold badges344 silver badges347 bronze badges asked Jul 2, 2014 at 21:54 Kenny BonesKenny Bones 5,13938 gold badges116 silver badges180 bronze badges 2
  • So is it integer or string? First you mentioned 'integer strings' next time only 'integer'? so what now? – Dávid Szabó Commented Jul 2, 2014 at 21:55
  • It's only integers, sorry – Kenny Bones Commented Jul 2, 2014 at 21:57
Add a ment  | 

3 Answers 3

Reset to default 6

If they're already strings, substr'll do the trick:

str.substr(2, 2);

If they're numbers, you can multiply and use Math.floor:

Math.floor(number * 100);

The fastest and easiest way:

number*100|0;

(| is bit wise OR and it will convert any number to an integer, thus behaving the same as Math.floor but shorter and faster.)

a couple of ways to do this

Math.floor(number*100);

Probably the most correct as you are working with a number the whole time.

parseInt(number*100, 10);

parseInt is supposed to take a string as first argument, but if you pass it a number javascript will convert to string.

(number+"").replace(/\d*\.(\d{2})\d*/, "$1");

Or convert to string and regex

发布评论

评论列表(0)

  1. 暂无评论