adding float in jquery - javascript

var sssee = "581.30";
var ssser = "1,178.70";
var ssee = sssee.trim().replace(/,/g, "");
var sser = ssser.trim().replace(/,/g, "");
console.log("ee " + ssee)
console.log("er " + sser)
console.log("total " + parseFloat(ssee + sser))
In log i see:
ee 581.30
er 1178.70
total 581.301178
Why is it when adding replace to remove the , messes the computation.

Variables ssee and sser are both strings. When you peform ssee + sser it would return string 581.301178.70 which would be passed to parseFloat function then. When there are two decimal points, only first is taken as correct, that's why parseFloat returns 581.301178.
Check the snippet with correct solution.
var sssee = 581.30;
var ssser = "1178.70";
var ssee = String(sssee).trim().replace(/,/g, "");
var sser = String(ssser).trim().replace(/,/g, "");
console.log("ee " + ssee)
console.log("er " + sser)
console.log("total " + (parseFloat(ssee) + parseFloat(sser)))
You should also wrap ssee and ssser in String object before using trim and replace methods. Without doing that if you provide those variables as floats, instead of strings, your code won't work.

Your problem:
You concatenate two strings ("581.30" + "1,178.70") to one string ("581.301178.70"). Then you parse it to a float (581.301178).
Solution:
You need to parse each one to a float at first. After do your addition (parseFloat(ssee) + parseFloat(sser)).

Related

Function that adds equal amount of whitespace to both ends of string

function space(str,numSpace){
str = "";
numSpace = (" " + " ");
document.write(numSpace + str + numSpace);
}
console.log(space("hi", " "));
This is not working out, I'm not too sure how I can add whitespace to both ends of a string.
This is not working out, i'm not too sure how I can add whitespace to
both ends of a string.
you're always resetting the parameter str to empty string hence the unexpected behaviour.
there are two ways you could solve the issue at hand.
1) you could use console.log() inside the method, example:
function space(str, numSpace) {
var result = numSpace + str + numSpace;
console.log(result);
}
space("hi", " ");
2) you could return the value then use console.log():
function space(str, numSpace) {
return numSpace + str + numSpace;
}
var result = space("hi", " ");
console.log(result);
Don't overwrite you're function's parameters with constants, and don't use document.write but return the result:
function space(str, numSpace) {
return numSpace + str + numSpace;
}
console.log(space("hi", " "));
Also I would suggest renaming numSpace to spaces, as the former suggests to be used with an integer count, not a string of spaces.

How to add spaces in the first and the end of a string variable

I'm trying to add spaces in the first and the end of this string variable, I tried to convert the string to an array, then add space with push() and unshift() ... but it returns "x.push is not a function"
function space_fb(x){
x.split(" ");Array.prototype.slice.call
x.push (" ") ;
x.unShift (" ") ;
return x.join(" ");;
}
var xxx = "Medardo";
space_fb(xxx);
alert(xxx);
There is many ways this can be done you could simply add the spaces in your string value for example like " Medardo " and it will work, But My example would handle dynamic string data.
You dont need that space_fb function at all its dead simple:
var xxx = " " + "Medardo" + " ";
alert(xxx);
Edited as OP wanted it in a function as his "teacher wants him to"
function AddSpaces(x){
return " " + x + " ";
}
var xxx = AddSpaces("Medardo")
alert(xxx);
How about this? JSON.stringify ist just to show the output in this way.
var x = "foo";
function addSpaces(string){
var a = string.split("");
a.push(" ");
a.unshift(" ");
return a.join("");
}
document.write(JSON.stringify(addSpaces(x)));
This is because you are using method split but the variable is not being assign
you have two options
1.- x = x.split();
or
2.- var myArray = x.split(" ");
This is all you will need do not use the + + operators. A . is a concatenation operator.
var xxx = ' '.xxx.' ';
As mentioned by #itsgoingdown, in JavaScript you can append strings using the + operator. There is really no need to split the string into a character array and push/unshift to add spacing.
function space_fb(x){
x.split("");Array.prototype.slice.call
x.push (" ") ;
x.unShift(" ") ;
return x.join("");;
}
var xxx = "Medardo";
space_fb(xxx);
alert(xxx);

Javascript splitting string in to two parts number and text safely

I was wondering if there is a safe way (if the data is coming from users) to get the string and the number separated - for example "something-55", "something-124", "something-1291293"
I would want:
something and
55
something and
124
something and
1291293
I mean by a 'safe way' is to be certain I am getting only the number on the end.. if the data is coming from the users "something" could be anything some-thing-55 for example..
I'm looking for a robust way.
try this, working.
var string = 'something-456';
var array = string.split('-');
for (var i = 0;i<array.length;i++){
var number = parseFloat(array[i]);
if(!isNaN(number)){
var myNumber = number;
var mySomething = array[i - 1];
console.log('myNumber= ' + myNumber);
console.log('mySomething= ' + mySomething);
}
}
Can you try this?
var input='whatever-you-want-to-parse-324';
var sections=input.split(/[\w]+-/);
alert(sections[sections.length-1]);
You can use substr along with lastIndexOf:
var str = "something-somethingelse-55",
text = str.substr(0, str.lastIndexOf('-')),
number = str.substr(str.lastIndexOf('-') + 1);
console.log(text + " and " + number);
Fiddle Demo
All though it's a tad late, this would be the most restrictive solution:
var regex = /^([-\w])+?-(\d+)$/,
text = "foo-123",
match = test.match(regex);
You will get a match object back with the following values:
[ "foo-123", "foo", "123" ]
It's a very strict match so that " foo-123" and "foo-123 " would not match, and it requires the string to end in one or more digits.

Javascript: replace inside a replace

My input is many lines of text that looks like this:
a.b.c.d.e (f:g)
I need to turn this into
a.b.c.d.e (a/b/c/d/e/f?g)
Note that the dotted part (a.b.c.d.e) can have varying numbers of elements, so sometimes it'll be q.r.s.t, sometimes u.v.w.x.y.z and so on. I have a replace() that will give me (a.b.c.d.e.f?g), but what I need is then to turn all those .s into /s in the result.
Is there a way to do a replace inside a replace? Or should I just call replace() on the string twice?
Sorry if this question is poorly worded, I'm not awfully well versed at regular expressions in javascript.
A very crazy way of doing it:
var str = "a.b.c.d.e (f:g)";
var re = /([^\s]+)\s\(([^:]+):([^\)]+)\)/;
var newStr = str.replace(re, function(a,b,c,d){ return b + " (" + b.replace(/\./g,"/") + "/" + c + "?" + d + ")"; });
jsfiddle
You need to chain the calls to replace() one after the other.
var result = source.replace("foo", "bar").replace("oof", "rab");
A saner way :) http://jsfiddle.net/smfPU/
input = "a.b.c.d.e.w.x.y.z (f:g:h)";
output = input.replace(/:/g, "?");
outputparts = output.split("(");
left = outputparts[0];
middle = left.replace(/\./g, "/").trim();
right = outputparts[1];
output = left + "(" + middle + "/" + right;
document.write(output);

Javascript string formatting, short question

How can I use javascript to add a number (any number between 0-100) followed by a underscore, before the variable value?
Example:
2000 becomes 12_2000 //a number of my choice is added followed by an underscore
hello becomes 12_hello
The number (12 in this case) is a constant chosen by me!
Thanks
i + '_' + x where i is the number and x is an arbitrary value.
Just use string concatenation:
var res = '12_' + myNum;
Or with a variable prefix:
var res = prefix + '_' + myNum;
This is just basic string concatenation, which can be done with the + operator:
var num = 2000;
"12_" + num;
// "12_2000"
var_name = "2000";
output = "12_" + var_name;
function prefixWithNumber(value, number) {
return number + "_" + value;
}
This expression is evaluated as (number + "_") + value. Since one of the operants in the first addition is a string literal, the second argument number is converted (coerced) to a string. The result is a string, which causes the third argument to be converted to a string as well.
This is what the JS engine does behind the scenes:
(number.toString() + "_") + value.toString();
Maybe you're looking for something like this:
Object.prototype.addPrefix = function(pre){
return pre + '_' + this;
};
This allows code like:
var a = 5;
alert(a.addPrefix(7));
or even:
"a string".addPrefix(7);
Joining an array can be faster in some cases and more interesting to program than "+"
[i, '_', myNum].join('')

Categories