String of numbers can't start with zero. Other Solutions? [duplicate] - javascript

This question already has answers here:
Remove leading zeros from a number in Javascript [duplicate]
(3 answers)
Closed 5 years ago.
I have a string that only contains numbers, but the string can not start with a zero.
The first thing I cam up with was this:
let myNumber = "0052";
myNumber = myNumber.split('');
for (let i = 0; i < myNumber.length; i++) {
if (myNumber[i] == '0') {
myNumber.splice(i, 1);
i--;
} else {
break;
}
}
console.log(myNumber);
console.log('result:', myNumber.join(''));
Everything works fine like that.
I thought there might be an other way without using a classical for-loop.
My attempt with a for-of loop failed. As soon as I remove the first entry of my array, the index of the loop does not reset, so it skips the second zero in my array. Here is the code for that:
let myNumber = "0052";
myNumber = myNumber.split('');
for (let n of myNumber) {
if (n == '0') {
myNumber.shift();
} else {
break;
}
}
console.log(myNumber);
console.log('result:', myNumber.join(''));
What other solutions to this problem are there? Is there a more performant solution?

What you're probably looking for is parseInt function.
const result = parseInt("0052", 10).toString();
console.log(result);
I also added toString() to convert number to a string. parseInt also accepts second argument - the radix. Read more about parseInt

Regexp: /^[0]+/
let myNumber = "0000000520";
console.log(myNumber.replace(/^[0]+/, ''))

Use
parseInt('0052') = 52
or
parseFloat('0052.29') = 52.29 if your number is float type:

I just have different and simpler approach than yours :)
while(myNumber.length){
if(myNumber.charAt(0) == '0')
myNumber = myNumber.substring(1, myNumber.length);
}
DEMO : https://jsbin.com/falejuruwu/1/edit?js,console

Related

Bean Counting WITHOUT using for loop and regex [duplicate]

This question already has answers here:
How to count string occurrence in string?
(40 answers)
Closed 2 years ago.
I tried to solve the following problem without using the for loop:
"Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters there are in the string.
console.log(countBs("BBC")); // → 2
Thank you for your help.
Here is the code I wrote so far which doesn't work:
function countBs(word) {
let count = 0
if (word.length == 0) {
return count;
} else {
if (word[word.length - 1] == 'B') {
count++
}
return countBs(word.slice(0, word.length - 1))
}
}
console.log(countBs("BBC"))
You can easily use regex for this case:
function countBs(word) {
const matches = word.match(/B/g);
return matches && matches.length || 0;
}
Basically it globally searches for occurrences of 'B'. If it find it, it returns the length of it, if the matches are null it will return 0.
Simpler less expressive:
function countBs(word) {
return (word.match(/B/g) || []).length;
}

How to remove all non-alphabet characters, javascript [duplicate]

This question already has answers here:
Java, Check if a String is a palindrome. Case insensitive
(5 answers)
Closed 5 years ago.
I am asked to check if a string is a Palindrome.
To not be case sensitive. To ignore all characters that are not letters.
My Answer
function palindrome(str) {
var oldStr = str.toLowerCase().replace(/\s+|\,|\.|\_|\-|\:|\(|\)|\/|\\/g, '');
var newStr = str.replace(/\s+|\,|\.|\_|\-|\:|\(|\)|\/|\\/g, '').split("").reverse().join("").toLowerCase();
if ( oldStr === newStr){
return true;
}
else {
return false;
}
}
palindrome("ininiNI");
The function is to be checked with any string possibility.
Example: ("0_0 (: /-\ :) 0-0") Which according to the requirements should return true.
I could not find a better solution in JavaScript then the one above.
Is there a faster/better way than just writing out each possible character to be removed/replaced? (especially since what I wrote is far from exhaustive...)
There is no need to call toLowerCase() and replace() twice. You can also cut string in a half, reverse one part and then compare. That way you can speed up your function few times at least.
Optimized function may look like that:
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-z]/g, '');
var max = str.length - 1;
for (var i = Math.floor(max / 2); i >= 0; i--) {
if (str[i] != str[max - i]) {
return false;
}
}
return true;
}
palindrome("inabcbani"); //true
palindrome("abcddcba"); //true
palindrome("a*#$(b)&^#%#%(*a"); //true
palindrome("abba"); //true
palindrome("abcdba"); //false
For loop will be the fastest way in my opinion as it's quick and simple. You can return false once you find first character that doesn't match.

Show numbers to second nearest decimal

I'm very new to Javascript so please bear with me.
I have this function that adds up a total. How do I make it so that it shows the nearest two decimal places instead of no decimal places?
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".row-total-input").each(function() {
var valString = $(this).val() || 0;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
}
Thank you!
Edit: As requested: commaFormatted:
function CommaFormatted(amount) {
var delimiter = ",";
var i = parseInt(amount);
if(isNaN(i)) { return ''; }
i = Math.abs(i);
var minus = '';
if (i < 0) { minus = '-'; }
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
amount = "$" + minus + n;
return amount;
}
Well parseInt parses integers, so you are getting rid of any decimals right there. Use parseFloat.
E.g.
parseFloat('10.599').toFixed(2); //10.60
You might also want to change your commaFormatted function to something like:
function commaFormatted(amount) {
if (!isFinite(amount) || typeof amount !== 'number') return '';
return '$' + amount.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
}
commaFormatted(0); //$0.00
commaFormatted(1.59); //$1.59
commaFormatted(999999999.99); //$999,999,999.99
Use to function toFixed(2)
The 2 is an integer parameter that says use 2 decimal points, assuming your comma formatted code does not turn it into a string. (If it does, fix the decimals BEFORE you run it through the formatting)
$("#product-subtotal").val(CommaFormatted(parseFloat(prodSubTotal).toFixed(2)));
Remember to parseFloat because the val() could be a string!`
You're looking for toFixed(). It takes one parameter, digits. The parameter is documented as follows:
The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.
Do also note that parseInt() parses integers, truncating any decimals you might have. parseFloat() will preserve decimals as expected.
I solved my problem. I simply changed:
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
to
$("#product-subtotal").val(prodSubTotal);
As I stated in the comments, this was not a script I wrote. It is a script Chris Coyier wrote and I was just trying to amend it. I guess I didn't need to use CommaFormatted for my purposes?
Thank you all for your help!

How to increment a numeric string by +1 with Javascript/jQuery

I have the following variable:
pageID = 7
I'd like to increment this number on a link:
$('#arrowRight').attr('href', 'page.html?='+pageID);
So this outputs 7, I'd like to append the link to say 8. But if I add +1:
$('#arrowRight').attr('href', 'page.html?='+pageID+1);
I get the following output: 1.html?=71 instead of 8.
How can I increment this number to be pageID+1?
Try this:
parseInt(pageID, 10) + 1
Accordint to your code:
$('#arrowRight').attr('href', 'page.html?='+ (parseInt(pageID, 10) + 1));
+ happens to be valid operator for both strings and numbers that gives different results when both arguments are numeric and when at least one is not. One of possible workarounds is to use operator that only have numeric context but gives same mathematical result, like -. some_var - -1 will always be same as adding 1 to some_var's numeric value, no matter if it is string or not.
$('#arrowRight').attr('href', 'page.html?='+ (pageID - -1));
All these solutions assume that your number you want to add 1 to is within the machine precision for an integer. So if you have a large enough number within that string when you add 1 to it won't change the number.
For Example:
parseInt('800000000000000000', 10) + 1 = 800000000000000000
So I wrote a quick solution to the problem
function addOne(s) {
let newNumber = '';
let continueAdding = true;
for (let i = s.length - 1; i>= 0; i--) {
if (continueAdding) {
let num = parseInt(s[i], 10) + 1;
if (num < 10) {
newNumber += num;
continueAdding = false;
} else {
newNumber += '0';
}
} else {
newNumber +=s[i];
}
}
return newNumber.split("").reverse().join("");
}
Now, using the same example above
addOne('800000000000000000') + 1 = '800000000000000001'
Note that it must stay as a string or you will lose that 1 at the end.
It needs to be a integer, not a string. Try this:
pageID = parseInt(pageID)+1;
Then you can do
$('#arrowRight').attr('href', 'page.html?='+pageID);
Simply, $('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The parentheses makes the calculation done first before string concatenation.
let pageId = '7'
pageId++
console.log(pageId)
Nowadays, you just need to pageID++.
Just change your order of operations by wrapping your addition in parentheses; if pageID is already a number, parseInt() isn't necessary:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
Demo
As long as your pageID is numeric, this should be sufficient:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The problem you were seeing is that JavaScript normally executes in left-to-right order, so the string on the left causes the + to be seen as a concatenator, so it adds the 7 to the string, and then adds 1 to the string including 7.

check if number string contains decimal?

After doing a sqrt()
How can I be check to see if the result contains only whole numbers or not?
I was thinking Regex to check for a decimal - if it contains a decimal, that means it didn't root evenly into whole numbers. Which would be enough info for me.
but this code isnt working...
result = sqrt(stringContainingANumber);
decimal = new RegExp(".");
document.write(decimal.test(result));
I bet there's other ways to accomplish the same thing though.
. means any char.
You have to quote the dot. "\."
Or you could test
if (result > Math.floor(result)) {
// not an decimal
}
You can use the % operator:
result % 1 === 0; // rest after dividing by 1 should be 0 for whole numbers
Use indexOf():
​var myStr = "1.0";
myStr.indexOf("."); // Returns 1
// Other examples
myStr.indexOf("1"); // Returns 0 (meaning that "1" may be found at index 0)
myStr.indexOf("2"); // Returns -1 (meaning can't be found)
"." has meaning in the regex syntax which is "anything" you need to escape it using "\."
If its a string we can just use split function and then check the length of the array returned. If its more than 1 it has decimal point else not :). This doesn't work for numbers though :(. Please see the last edit. It works for string as well now :)
function checkDecimal() {
var str = "202.0";
var res = str.split(".");
alert(res.length >1);
var str1 = "20";
alert(str1.split(".").length>1);
}
Hope it helps someone.
Happy Learning :)
Are you looking for checking string containing decimal digits ,
you can try like this
var num = "123.677";
if (!isNaN(Number(num)) {
alert("decimal no");
}
else {
alert("Not a decimal number");
}
I am sorry. This answer is too late. but I hope this will help.
function isThisDecimal(val){
if (!(val.indexOf(".") == -1)){
return true; // decimal
}
return false; // number
}
console.log(isThisDecimal("12.00")); //true
console.log(isThisDecimal("12.12")); //true
console.log(isThisDecimal("12"));// false

Categories

Resources