I have $45.00 as string and need to get 45 out of that.
following is working...
How do I write this in one line?
var x= "$45.00" ,cents =/\.00$/;
var z= x.replace(/^\$/,'');
z = z.replace(cents,'');
Basically, the .replace() calls can be daisy-chained, with the second one acting on the results of the first:
var x = "$45.00", cents = /\.00$/, z = x.replace(/^\$/, '').replace(cents, '');
If the question is that straight forward you can simply use this one line to get the left of the dot value.
var x= "$45.00".split('$')[1].split('.')[0];
Explanation:
You assign the variable x to the price string in this case
"$45.00"
Then use the string function split, to divide the string into two
arrays.
Right now you have ["$"] in position zero and the rest in position 1
["45.00"]
You then use the same function on the second array at position one
to divide at the dot character.
Now you have at position zero ["45"] and position 1 [".00"]
You need position 0 so that's the index you you will use and that's
it.
I think it's pretty straightforward but tried to be as through as possible.
Related
I'm very new to programming and have been a bit shy when it comes to asking for help....to be honest, I get intimidated by how fast others can figure something out, so for those of you that are in the category, I was hoping you could help me out with a homework question. I Don't know where to begin or write the pseudocode, but if you can guide me or give me a response with details of the why and how, I'd owe you a huge debt. Here's the problem:
we define the following operations on a string:
left shifts: a single circular rotation of the string in which the first character becomes the last
character and all other characters are shifted one index to the left. For example, bcdea becomes
cdeab after a left shift.
right shifts: same as above but in reverse, the last character becomes the first.
the following parameters:
s: string to shift
left shift: integer
right shift: integer
constraints:
1 <= s <= 10^5
0 <= leftshifts, rightshifts <= 10^9
function getShiftedString(s, leftShifts, rightShifts) {
}
function getShiftedString(s, leftShifts, rightShifts) {
s = leftShifting(s, leftShifts);
return rightShifting(s, rightShifts);
}
function leftShifting(s, leftShifts) {
return s.substring(leftShifts) + s.substring(0, leftShifts);
}
function rightShifting(s, rightShifts) {
let l = s.length - rightShifts;
return leftShifting(s, l);
}
try this
Try writing it out in psudo code, that'll help you plan your function.
Think about what you need this function to do, you need it to:
accept a string
shift it to the right x number of times,
shift it to the left y number of times
so maybe your psudo code would look a little like this
s = string, x = left, y = right
convert s to array
for (x times)
q = first element in array
remove first element from array
add q to end of array
for (y times)
q = last element in array
remove last element from array
add q to the beginning of the array
make s string again
return s
Then it's just a simple matter of converting that to code.
Keep in mind, that's just one solution, and there are far better ones out there. definitely do what Neil Lunn said though, and look up string shifting.
When I use p=10000 ,r=15 and n=60 in the below ...
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100).toFixed(2));
x = 237.9 instead of 237.90.
If the combo of p, r and n result in a number that is not $xx.x", then the code snippet works fine ...ie. formats to 2 decimal places.
But why is it displaying 237.9 instead of 237.90?
When you call number.toFixed(2), you do indeed get a string representation of the number with two decimal digits:
var number = 237.9;
number.toFixed(2); // '237.90'
However, when you then use parseFloat on this, you convert it back to a number again; since a number does not contain information about the number of zeros to display, the last zero is dropped as it is printed:
parseFloat(number.toFixed(2)); // 237.9
To avoid this, simply don't convert your string back into a float, but use it as a string.
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
p=10000,r=15, n=60;
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
console.log(x)
Add toFixed after all operations. You need string, basically...
I want to set a cursor in javascript so when I use regex, it recognizes what data it has already parsed, and continues from that point. Below is a snippet of code that shows what the file is like.
# vtk DataFile Version 4.0
-3659.0757 3746.6780 3628.1143
-3659.6714 3746.2517 3627.9539
-3660.1450 3745.8142 3627.9270
-3660.4631 3745.3735 3628.0605
-3660.6931 3745.0708 3628.1416
LINES 207 31529
581 0 1 2 3 4 ... 579 580
Currently I pick up the float float float pattern correctly, and I want my code to continue to LINES 207 31529 and then 581. This code picks up LINES, but instead of going to the 581 it goes back to the top of the file and takes 4 for numLines.
var LINES = /(LINES)[ ]+[\d]+[ ]+[\d]+[\n]/;
var recogLines = /[\d]+/;
var numLines = parseInt(recogLines.exec(data));
I saw something online about \G, but I don't think javascript recognizes that (or I'm just not using it correctly). How do I keep a cursor so the same data isn't iterated over and over again? Thanks!
I would suggest something along the lines of (may not be exactly syntactically correct):
var LINES = '/(LINES)[ ]+([\d]+)[ ]+([\d]+)\n/';
var data = <input>;
var output = new Array();
result = LINES.exec(data);
while(result) {
output.push([result[1], result[2], result[3]]);
result = LINES.exec(data.substring(result.index + result[0].length);
}
but at that point, I would use the global modifier:
var LINES = '/^(LINES)[ ]+([\d]+)[ ]+([\d]+)$/gm';
result = LINES.exec(data);
would give you an array:
array[0][2] // first LINE, first set of numbers
array[0][3] // first LINE, second set of numbers
array[1][2] // second LINE, first set of numbers
array[1][3] // second LINE, second set of numbers
Just my 2 cents.
Edit:
If you are writing a parse, I could see the reason for the first. Just add your code to parse the lines (and keep track of your cursor position) before running your pattern match again, and pass that to the substring instead of the index of the previous match plus the length of the match.
I am making a basic game, and I have a tile system that I'm using. Each tile has an ID of "tileX", where X is a number (ex. tile1). I have a function as follows:
window.onclick = function() {
var x = event.clientX, y = event.clientY,
elementMouseIsOver = document.elementFromPoint(x, y).id;
document.getElementById("tileTell").value = elementMouseIsOver;
console.log(elementMouseIsOver);
console.log(typeof(elementMouseIsOver));
elementMouseIsOver = parseInt(elementMouseIsOver);
console.log(elementMouseIsOver);
console.log(typeof(elementMouseIsOver));
}
Line 4 of code there fills in an input field so I can visually see which tile I've clicked (I'm using this to make sure things are working properly and so I can find the tiles I need). That works fine. On line 5 when I do a console.log, it gives me the proper ID, and verifies that it is a string.
After that I want to reset the elementMouseIsOver variable to be an integer, so if the ID was tile1 I would expect the new result to be 1. But when I look at it in the console, I get NaN. And then when I check the type of it immediately after that, I get number.
The parseInt does not seem to be working properly, what am I doing wrong? I need to use the ID names of each tile for mathematical operations so this is vital to my game. I know it's probably a really dumb mistake but I am completely at a loss...
If you want parseInt() to work on strings in the way you're using it, it has to start with a digit; in your case, it starts with alphabetical characters, and so (with an implicit radix of 10) it will rightfully return NaN.
You could get the number out by using a generic method:
var num = +(elementMouseIsOver.match(/\d+/) || [])[0];
It matches the first group of digits it can find and then uses the unary plus operator to cast it into an actual number value. If the string doesn't contain any digits, it will yield NaN.
In your particular case, you could also apply parseInt() on the part that immediately follows "tile":
var num = +elementMouseIsOver.substr(4);
NaN is correct.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.
Nothing parsed successfully.
EDIT
You could accomplish what you want by removing the non-numeric characters from the string, assuming you'll always have a string+integer as the ID. Try this:
parseInt(elementMouseIsOver.replace(/[^\d]/,""))
You need to remove the "tile" string first, so it can properly parse the value:
elementMouseIsOver = parseInt(elementMouseIsOver.substring("tile".length));
.substring("tile".length) returns a substring starting with the character after "tile" (position 4 in the string, count starts at 0), resulting in only the number of the ID (as a string).
fiddle: http://jsfiddle.net/rk96uygd/
The typeof of a NaN is number.
Use isNaN() to test if a value is NaN or Not a Number
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
You could also use the Number() cast instead of parseInt().
you trying to parseInt on a element ID that is non-numeric, when parse fail it will return NaN (*or not a number*)
elementMouseIsOver = parseInt(elementMouseIsOver);
moreover, your elementMouseIsOver is an ID of control, I don't think .value can get the value of control
elementMouseIsOver = document.elementFromPoint(x, y).id;
I have two variables holding integer values:
x = 36,000;
y = 18,045.40;
this is how i subtract:
z = parseInt(x) - parseInt(y);
the result is 15.
If i remove the parseInt the result is 'Nan'.
How do I go about subtracting x with y without rounding off or removing thousands?
many thanks.
Don't put commas in your numbers.
The code you have posted won't even run. I would recommend pulling the ,s out of your numbers and using parseFloat instead. This appears to give the result you want. Demo here:
http://jsfiddle.net/yVWA9/
code:
var x = 36000;
var y = 18045.40;
alert(parseFloat(x) - parseFloat(y));
There is no separator for thousands in Javascript. Your variables are either holding strings and not integer values or you are getting syntax error.
If you have strings and they cannot be changed (like received from service, etc.) then try this:
x = "36,000";
y = "18,045.40";
// remove commas and convert to numbers
function norm(num) { return +num.replace(',', ''); }
console.log(norm(x) - norm(y));