带有逗号的JS parseInt字符串

时间:2016-05-12 10:55:48

标签: javascript

我有一个包含4个数字的字符串,中间有逗号。我想将此字符串转换为int,但我想保留逗号。

function CreateCanvas() {
                var canvas = document.getElementById("myCanvas"); // grabs the canvas element
                var context = canvas.getContext("2d"); // returns the 2d context object
                var imgageObj = new Image() //creates a variable for a new image


                var intCoor = 0;
                var Coor = "80,80,4,3";
                intCoor = parseInt(Coor);
                console.log(intCoor); // outputs 80

                imgageObj.onload = function() {
                    context.imageSmoothingEnabled = false;
                    context.drawImage(imgageObj,intCoor); // draws the image at the specified x and y location
                };
                imgageObj.src = "img/9.png";   
            }

我希望输出为80,80,4,3。不是80或808043.

编辑:抱歉,我忘记了我需要数字80,80,4,3作为画布的坐标。

2 个答案:

答案 0 :(得分:1)

你不能这样做..改为使用RegEx。

var price = "1,50,000";
var priceInNumber = parseInt(price.replace(/,/g, ''), 10);

答案 1 :(得分:1)

你唯一能做的就是在80使用parseFloat之后的第一个逗号浮动之后创建第一个数字(包括.的浮动数字),直到你替换为逗号由"。"。

var intCoor = parseFloat(Coor.split(",").join("."));

其他一些选项是将每个数字保存在不同的序列数组中,通过调用split轻松生成:

var intCoor = Coor.split(",");

所以你可以通过声明键来获得每个分开的数字。

intCoor[0] // -- returns 80, the first number
intCoor[1] // -- returns 80, the second number
intCoor[2] // -- returns 4, the third number
intCoor[3] // -- returns 3, the forth number