Trim long number in JavaScript - javascript

For example, I got that long nubmer 1517778188788. How can i get first 6 digits from that number, like 151777 and trim another digits?

Just convert a number to string and then slice it and convert it back to Number.
const a = 1517778188788;
const str_a = a.toString();
const result = Number(str_a.slice(0, 6));

new String(your_number).substring(0,6)
(basically converting it to a string and substringing it). Don't forget to parse it back afterwards

Applicable only when you want to strip last 7 digits, and the numbers have constant length (13 in this case). Still leaving you with first 6 ones though.
const nr = 1517778188788;
const result = Math.floor(nr / 10000000)

Try this:
var num = 1517778188788; // long number
var str = num.toString(); //convert number to string
var result = str.substring(0,6) // cut six first character
result = parseInt(result); // convert it to a number
here is a working fiddle

Related

How to get the number before percentage symbol in a string?

These are some possible strings. The number percentage is always at beginning.
var string = "0.5% - corresponding something" or var string = "23% - correspondig something";
I need to get the the entire number before the percentage symbol.
I already tried some solutions in cutting the string, but the problem is that the number doesn't have always the same length.
Can you help me?
There are several solutions. For example:
let antani = "23% - correspondig something";
// using parseFloat
console.log(parseFloat(antani));
// using split
console.log(antani.split("%")[0]);
first split string using '%'
<script>
var str = "0.5% - corresponding something";
var res = str.split("%");
number=res[0];
console.log(res[0]);
</script>
Using Regular expression you can match the numbers (including dots) before the percentage sign.
Example:
var text = "0.5% - corresponding something";
var percentageRegex = /([0-9\.]+).+/;
var matches = percentageRegex.exec(text);
console.log(matches[1]);

How to print out the even numbers in reverse order?

var num = prompt("Enter an integer : ");
var reversenum = num.reverse('');
document.write(reversenum);
I want to print out the even number of integers in reverse order after inputting an integer through the prompt, but I have no idea.
Even if I try to write split(), I don't think I can separate it because the letters are attached to each other. What should I do?
The result I want is,
Enter an integer : 8541236954
46248
Based on your updated question, I suppose what you want is to extract even-valued digits from a given integer, and display them in reverse order.
Since prompt() always returns a String, you can do one of the two ways to split it into digits and reverse their order:
Old-school JS way: num.split('').reverse()
ES6 array spread way: [...num].reverse()
Then, it is just a matter of using Array.prototype.filter() to return even numbers. Even numbers can be selected based on the criteria that their modulus of 2 is always 0 (i.e. when number is divided by 2, it has a remainder of 0).
Finally, join your filtered array so you get a string again.
See proof-of-concept order below:
const num = prompt("Enter an integer : "); // e.g. try '8541236954'
const digits = [...num].reverse();
const evenDigits = digits.filter(d => d % 2 ===0);
console.log(evenDigits.join('')); // e.g. '46248'
You need to first split the string into an array of characters, reverse the array and then join it again. I have given an easy to understand code which converts every character of the reversed string to an int and checks if that integer is even, followed by concatenating it in the answer.
var num = prompt("Enter an integer : ");
var reversenum = num.split('').reverse().join('');
var ans = "";
for (var i = 0; i < reversenum.length; i++)
{
var x = parseInt(reversenum[i]);
if(x%2 === 0)
ans = ans.concat(reversenum[i]);
}
console.log(ans);

Javascript: How cut out part of an integer?

How to cut out part of an integer?
What can i do to get an integer 12 or 123 from a variable n
let n = 123456;
A simple way to do this would be to just cast the input number to a string, and then take a substring:
var n = 123456;
n = n + "";
var output = n.slice(0, 2);
console.log(output);
Another approach, if all you want is to get some number of leading digits, would be to divide by the correct multiple of ten, e.g.
var n = 123456;
var output = Math.floor(output / 10000);
The strategy I suggest is to convert the integer value to a string which you may manipulate with parseInt() as well as the string's substr() method, as follows:
const START = 0;
const first_two = 2;
const first_three = 3;
const base_ten = 10;
let n = 123456;
let res = parseInt( String( n ).substr( START,first_two ),base_ten );
console.log(res);
res = parseInt(String( n ).substr( START,first_three ),base_ten );
console.log(res);
The Number Object has a toString() method but apparently it is safer to convert the integer to a string by passing the integer value of n to the String Object per this discussion. You may then use the String Object's substr() method to access the first two or three digits appearing in the string. Next, you may take the resulting numeric string and pass it to parseInt(), along with a base parameter to obtain the integer value.
I think this will work for you - you first change it to string and split it to an array and then remove the unwanted characters, then join the array together, and parse it as an integer: (edited to reflect #VLAZ's comment.
parseInt(n.toString().slice(0,2)));

How to get ASCII of number in JavaScript?

I am aware of name.charCodeAt(0). I am having issued with the following code, so I want a solution for below.
var number= 2;
var t = number.charCodeAt(0);
console.log(t);
The answer needs to be in ASCII. I am getting the log as 2 and not as ASCII value 50. What can be the issue?
ASCII is a way of representing String data. You need to first convert your Number to String;
Remember also that String can have arbitrary length so you'll need to iterate over every character.
var x = 2,
str_x = '' + x,
chrs = Array.prototype.map.call(str_x, function (e) {return e.charCodeAt(0);});
chrs; // [50]
Finally, JavaScript works with UTF-16/UCS-2 and not plain ASCII. Luckily the values for digits are the same in both so you don't have to do any further transformation here.
You have to cast a number to a string first to use .charCodeAt to get the numerical character code.
var number = 2;
var t = String( number ).charCodeAt( 0 );
console.log( t ); // 50
Just convert the number to String and call the method on it.
var number = 2;
var numberInString = number.toString();
var code = numberInString.charCodeAt(0);
console.log(code);

Read numbers from <pre>

I am trying to calculate certain numbers in an array of numbers in a pre tag. Such as count how many of the numbers are 7 or higher.
For example, I have this
<pre class="data">2 7 3 1 2
6 6 2 5 3
8 2 5 9 9
5 10 5 6 10
2 10 3 </pre>
I've figured out how to get to the numbers in a general way:
document.getElementsByTagName ('PRE')[0].firstChild.data = document.getElementsByTagName ('PRE')[0].firstChild.data.replace (/\t+$/, '')
But I do not know how to get at the individual numbers. Is it an array? Or a list of numbers that I need to parse by space?
I've looked at this thread: Using <pre> tag to display data in columns? and tried to use a for loop grabbing $entry[i], but I am not able to read individual numbers.
The following will give you a 2-dimensional array:
var str = document.getElementsByTagName('pre')[0].textContent;
str // take the string and
.split('\n') // break it into an array of lines;
.map(function(line) { // then transform each line by
return line // taking the line,
.trim() // removing leading and trailing spaces,
.split(/\s+/) // and breaking it into an array at whitespace,
.map(Number); // with each piece cast to a number.
});
http://jsfiddle.net/Lwkw4ee4/
String.prototype.trim = function() { // just in case of an old browser
return this.replace(/^\s+|\s+$/gm,'');
}
var str = document.getElementById('data').innerHTML.trim();
var data = str.split(/\s+/);
alert(data);
data will be an 1D array of numbers (to be accurate - strings with numbers, but it does not matter - it is easy to cast).
http://jsbin.com/mepulu/2/edit
var text = document.getElementsByClassName('data')[0].innerHTML; // Text
var values = text.split(/\s+/); // Array of strings
var numbers = values.map(function(num) {
return parseInt(num, 10);
});
numbers; // Array of integers
The content of the pre tag is just text. In order to access the numbers, you have to parse the text. I'm assuming you just need the list of numbers, and there is no significance to the columns.
If this is true, what you need to do is split the text on whitespace, and then process each item:
var number_string = document.getElementsByTagName ('PRE')[0].firstChild.data;
var numbers = number_string.split(/[\s]+/);
var a_number;
for (var i = 0; i <= numbers.length; i++) {
a_number = parseInt(numbers[i]); // assuming the numbers are whole numbers.
}
Note that numbers[i] is actually a string representation of the number, so you need to use parseInt(numbers[i]) to get the real number. (or parseFloat(numbers[i]) if they are not whole numbers)
Hope that's helpful.
Jay

Categories

Resources