Split() integer with Javascript

Asked

Viewed 6,999 times

7

Valor = 19.90;

MyArray = valor.split(".");

the code hangs , whole variable, however if,

Valor = "19.90";

MyArray = valor.split(".");

alert(MyArray[0]) = 19;
alert(MyArray[1]) = 90;

I would like to know how to use the split in int variable , thank you.

According to solutions, from friends already reputed below, I edit my question to the following form.

No, in the above case, I have the function,

function splitNum (34.50 * 2){
var s = n.toFixed(2).split('.');
var n1 = parseInt(s[0], 10); // 19
var n2 = parseInt(s[1], 10); // 10
return n1+"."+n2;
}

will return me 69.0

But I need you to return 69.00 , how would that be possible ? thank you.

Settled, thank you have a great afternoon.

function splitNum (34.50 * 2){
var s = n.toFixed(2).split('.');
var n1 = parseInt(s[0], 10); // 19
var n2 = parseInt(s[1], 10); // 10
return s[0]"."s[1];
}
  • 1: Javascript does not work with "int variable" - 2: you can create your own method .split() just like the original easily, see in my reply how.

  • try something like that: Valor = 19.90;MyArray = (valor).toString().split(".");

  • 2

    XY problem... If all you wanted was to format a number with two decimal places, just do Valor.toFixed(2). You didn’t have to split up and then put it back together... :)

  • 1

    rsrsr , I’ve used v.toFixed(2); is that I use other functions besides this, rsrsr, thank you.

7 answers

8


The split applies only to strings, not to numeric types. If you have a number with 2 decimal places (or only interested in the first 2 decimal places) you can turn it into a Sting using toFixed.

Valor = 19.90;
Valor.toFixed(2); // "19.90"

var valor2 = 1/3;
valor2.toFixed(2); // "0.33"

0.123456789.toFixed(5); // "0.12345"

From there you can apply the split. Remembering that if you want to convert back to integer*, it is important to specify the basis:

var s = Valor.toFixed(2).split('.');
parseInt(s[0], 10); // 19
parseInt(s[1], 10); // 10

// O que acontece se você omitir a base?
var s = 0.01.toFixed(3).split('.'); // ["0", "010"]
parseInt(s[1]); // 8! (começou com zero, então ele interpreta como octal)

*Remembering: if you want! If what you want is a string yourself, don’t convert back using parseInt, only use the values s[0] and s[1] however you see fit.

  • 3

    Best answer. + 1 by using the method .toFixed()

  • With your solution, if decimal returns 0 , it gets only 1 number, I need to keep 2 numbers, ex: If 0 equals 00 , would be like ?

  • @I’m sorry, I don’t understand. Do you speak of the whole or the fractional part? From what I’ve tested, the fractional part is correct, you want to make a padding throughout?

  • No, in the above case, I have the function, Function splitNum (34.50 * 2){ var s = n.toFixed(2). split('.'); var n1 = parseint(s[0], 10); // 19 var N2 = parseint(s[1], 10); // 10 Return n1+"."+ N2; } Will return me 69.0 , I need you to return 69.00

  • @Wilsonlavrador I suggest editing your question instead of answering in the comments. There is more space to explain, and other people can see too.

  • @Wilsonlavrador my answer meets your request for the need of decimal places

  • @Wilsonlavrador Got it now. See my updated response.

Show 2 more comments

4

No need to convert to string if the value is numeric.

valor = 19.90;
aValores = [parseInt(valor),Math.ceil((valor  % Math.floor(valor)) * 100)];

2

Just convert you to string before using the split.

There are several ways to convert a number to string, for example:

var n = 10.01;
var s = n.toString();
var a = s.split('.');

By the way, you use the term int and whole to refer to a number that is not integer. These terms are used only for integers (e.g. 1, 2, 3, 4, ... 1000) and not for rational numbers (e.g. 19.90).

EDIT This part of the answer is wrong, read the comments to understand. You might still want to turn the numbers, after the split, back into numeric type:

var n1 = parseInt(a[0]);
var n2 = a.length > 1 ? parseInt(a[1]) : 0;

The solution in the end would look like this

function SplitNum(n)
{
    var s = n.toString();
    var a = s.split('.');
    var n1 = parseInt(a[0]);
    var n2 = a.length > 1 ? parseInt(a[1]) : 0;
    return [n1, n2];
}

The correct way to turn into numbers back, would be to keep what comes after the decimal separator, after decimal separator:

var n1 = parseInt(a[0]);
var n2 = a.length > 1 ? parseFloat('0.'+a[1]) : 0;
  • 1

    does not work correctly: Splitnum(19.90) -> [19, 9]. The correct would be [19, 90].

  • 1

    I thought you wanted in number form, the digits 0 after the right comma are implicit in a numeric variable.

  • If you want to set the number of decimals, then you have to work with strings. See reply do @mgibsonbr.

  • 1

    @Miguelangelo +1 This is correct! I had suggested the toFixed in my answer as a means of getting around it, but in fact semantically 0.9 is the same as 0.90. It only makes a difference that you are saving the second value as "cents" (for example).

  • @Miguelangelo @mgibsonbr is right that the 19.90 -> 19.9, ok. But I mean the correctness of the program. It may not infringe on any mathematical-logical rule, but even be wrong about its purpose. And in this case, the result 90 would be misinterpreted as 9.

  • in the case, SplitNum(19.90)[1] == SplitNumNum(19.09)[1] // true, what is completely wrong. another example: SplitNum(19.91)[1] - SplitNum(19.90)[1] // 82!!

  • 2

    @Andréfigueiredo It took a lot to drop, but you’re right! If someone does SplitNum(19.90) and SplitNum(19.09) the results will be identical. P.S. I was already going to comment on this, but you were faster rsrs

  • @mgibsonbr: true! So the final part of my answer is wrong. I’m going to put a <s> in this part.

  • I remade the final part in a way that at least is not incorrect as it was before.

  • @If you’re going down that road, use it parseFloat. parseInt in a number beginning with "0." will always be zero.

  • @mgibsonbr: Exactly... corrected! = D

Show 6 more comments

1

As explained in the MDN, the split() serves to separate strings, and what you’re trying to do is separate an integer. What you can do is convert the integer to string:

var n =  123456789;
var digits = (""+n).split("");

Note that this will return you a string array, not an integer.

1

Solution

You first need to turn the int/double into string for example:

Valor = 19.90;

MyArray = String(Valor).split(".");

alert(MyArray[0]) // 19

alert(MyArray[1]) // 9 que no decimal é a mesma coisa que 90

1

You can try something like:

var Valor = 19.9;

var Dados = $.map( Valor.toString().split("."), function(v){
    return parseInt(v); 
});

jQuery.map() - https://api.jquery.com/jQuery.map/

1

To answer your question "Split integer with javascript":

It is not possible. Even because Javascript does not work with Integer(Integer) numbers, it only works with Number(floating number).

But I see that you want a method that does this for you without you using lines of code, because it’s the goal of .split(), then I will provide you with a function assigning her to Number.prototype so that you can use it in the same way as the .split():

Number.prototype.split = function(){
  var a = this.toString().split(".");
  return [parseInt(a[0]),(a[1].length > 1) ? parseInt(a[1]) : (parseInt(a[1])*10)];
} 
var Valor = 19.90;
Valor.split(); //retorna um array [ 19, 90 ]

var Valor = 19.95;
Valor.split(); //retorna um array [ 19, 95 ]

var Valor = 19.957;
Valor.split(); //retorna um array [ 19, 957 ]

Note that it ignores zero at the end because it is a Number and speaking in numbers 19.90 is the same thing as 19.9, so I did a check if the number size is greater than 1 it multiplies by 10 so always having your "zero" you want.

  • Your verification by length really meets the case of OP. It is not a generic code (none of the answers is - including mine) because without the use of toFixed some results will be incorrect (ex.: 19.090). But in this particular case it’s OK

Browser other questions tagged

You are not signed in. Login or sign up in order to post.