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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.