Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS parseInt string with commas

Tags:

javascript

I have a string with 4 numbers with commas in between. I want to convert this string to an int, but I want to keep the commas.

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";   
            }

I want the output to be 80,80,4,3. Not 80 or 808043.

Edit: Sorry i forgot to sa that I need the numbers 80,80,4,3 as coordinates for a canvas.

like image 727
Sonny Avatar asked Sep 03 '25 09:09

Sonny


2 Answers

You cannot do that.. Use RegEx instead.

var price = "1,50,000";
var priceInNumber = parseInt(price.replace(/,/g, ''), 10);
like image 103
Vinay Avatar answered Sep 04 '25 22:09

Vinay


The only thing you can do is to make the first number after the first comma float after the 80 using parseFloat (that include floating numbers of .), until you replace the commas by ".".

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

Some other option else is to keep each number in different arrays of sequence, easily generated by calling split:

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

So you can get each separated number by declaring keys.

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