How to convert a string to number using Google App

2019-02-16 13:42发布

I know that I'm asking a dumb question, but I can't figure it out how to convert this string 82144251 to a number.

Code:

var num = "82144251";

If I try the code below the .toFixed() function converts my number back to a string...

Question update: I'm using the google apps script editor and that must be the issue...

num = parseInt(num).toFixed() // if I just do parseInt(num) it returns 8.2144251E7

6条回答
再贱就再见
2楼-- · 2019-02-16 14:01

No questions are dumb.

a quick answer:

to convert a string to a number you can use the unary plus.

var num = "82144251";

num = +num;

Doing num = +num is practically the same as doing num = num * 1; it converts the value in a to a number if needed, but after that it doesn't change the value.

查看更多
虎瘦雄心在
3楼-- · 2019-02-16 14:01

It looks like you're looking for the Number() functionality here:

var num = "82144251"; // "82144251"
var numAsNumber = Number(num); // prints 82144251
typeof num // string
typeof numAsNumber // number

You can read more about Number() here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

Hope this helps!

查看更多
Summer. ? 凉城
4楼-- · 2019-02-16 14:06

You can convert a string to number using unary operator '+' or parseInt(number,10) or Number()

check these snippets

var num = "82144251";
num=+num
console.log(num);
var num2="82144251"
console.log(parseInt(num,10));

var num3="34";
console.log(Number(num3));

Hope it helps

查看更多
我命由我不由天
5楼-- · 2019-02-16 14:08

I use num-0, since it is easier for inline use.

查看更多
贪生不怕死
6楼-- · 2019-02-16 14:19

var intNum = parseInt("82144251", 10); // intNum is number

查看更多
一夜七次
7楼-- · 2019-02-16 14:20

var num = "82144251";
num = parseInt(num).toFixed()
console.log(num, typeof num); // string
num = parseFloat(num);
console.log(num, typeof num); // number

查看更多
登录 后发表回答