How do I cast a decimal number to String in Javascript? - javascript

325.234 to string?
is it toString()?

Simplest way, concatenate it with an empty string:
325.234 + '';
Which will implicitly call toString() on the number.
You could also use:
String(325.234);
And:
325.234.toString();

Sure, why not just:
325.234.toString()

or String(325.234)

var number = 123.54
var string = number.toString();
The "toString()" method is called implicitly when you use a non-string as part of a string concatenation. Such as:
var newString = "Hello " + number;

Related

Converting a number to s string in JavaScript using the + operator?

I know that if either one of my operands is a string, it should prefer string concatenation, but I get an integer.
var number = 134324;
var num_str = number + "";
console.log(num_str);
No it should not return string .. as you are printing it in console it looks like integer but try using
var number = 134324;
var num_str = number + "";
console.log(num_str);
typeof(num_str);
It will display that your answer is string ... :) hope you satisfied ..
You can use toString() method.
num_str = number.toString()

Javascript getting number from string

I have a string:
var example = 'sorted-by-' + number;
Where number variable can be any positive integer. I don't know how to reverse this process, not knowing how many digits this number has. I want to get from example string a number at the end.
var outputNumber = example.substring(10);
This is the simple solution because example string always start with 'sorted-by-'.
let num = + string.substr(10);
You can use String#replace function to replace sorted-by- to empty string and after that convert left part to a number:
var example = 'sorted-by-' + 125;
var num = +example.replace('sorted-by-', '');
console.log(num);
You can split string at - and get last element using pop().
var example = 'sorted-by-' + 100.99
var n = +(example.split('-').pop())
console.log(n)
You can also use regex for this.
var number = 245246245;
var example = 'sorted-by-' + number;
var res = example.match(/^sorted-by-(\d+)/);
console.log(+res[1]);

How do you sum two values containing the dollar sign "$"? I have been trying to figure out the methods and properties, still no clue

//for example
allInputs[22].value //equals $45 and
allInputs[4].value // equals $70
allInputs[22].value + allInputs[4].value = "$45$70"
It equals "$45$70". But I only want to sum up the value. how do I sum up both values to get the final value ignoring the dollar sign?
You can use
"$" + (parseInt(allInputs[22].value.substring(1)) + parseInt(allInputs[22].value.substring(1)))
The substring method, will get rid of the $ sign, and parseInt will convert it to a number. You need that, because if you do not use that it will concatenate the values as strings. Note that i put another set of brackets to sum the numbers. That is because, when the interpreter sees the "$" it thinks it should concatenate strings. But we want to sum the numbers and then concatenate the sum with the "$" string.
You can use reduce and check for a non-number sign at the beginning of a value:
var allInputs = ["$45","$70"];
var sum = allInputs.reduce(function(pre, curr){
if(isNaN(curr[0]))return pre+(+curr.slice(1));
return pre+curr;
},0);
console.log('$'+sum);
This is a general function expression that accepts the string value from a form input and returns a number.
const getNumber = (val) => Number(val.match(/[\d\.]+/));
You can use it like this:
const sum = getNumber(allInputs[22].value) + getNumber(allInputs[4].value);
DEMO
Note: ideally you should store the currency value ($, £, € etc) separately from the values so this doesn't become an issue.
I guess you need parseFloat(). Accordingly the following would be my helper function.
function addDollars(s1,s2){
var n1 = parseFloat(s1.replace(/[^0-9\.]/g,"")),
n2 = parseFloat(s2.replace(/[^0-9\.]/g,""));
return "$"+ (n1+n2).toFixed(2);
}
console.log(addDollars("$123.42","$12.88"));
You can use
parseFloat(allInputs[22].value.slice(1)) + parseFloat(allInputs[4].value.slice(1))
Remember that string are arrays.
if you want to end up with the "$" sign then just concatenate it.
You need to remove the "$" and convert the strings into numbers to sum them up.
Code
You can remove the "$" with replace like allInputs[22].value.replace('$', '') this will return "42" as a string.
Now we need to convert this string into a number. There are many ways to do this. I use Number() in the following solution.
Solution
var someMoney = '$50'
var moreMoney = '$60'
var toMuchMoney = "$" + Number(someMoney.replace('$', '')) + Number(moreMoney.replace('$', ''))
console.log(toMuchMoney)
To solve this, You should know about the difference between concatenation and addtion in javascript.
If you add two strings, You get concatenation of both strings as answer
"$45" + "$70" = "$45$70"
If you add two integers, you get addition.
45 + 70 = 115
So, to solve your problem, You need to first extract numbers from your variables and then do addition on them.
To extract numbers you can use any method but I am using split.
To convert string into integer you can use parseInt
let num1 = "$45";
let num2 = "$70";
function getValue(num) {
return parseInt(num.split('$')[1]);
}
let sum = getValue(num1) + getValue(num2);
console.log("$" + sum);

how can i replace first two characters of a string in javascript?

lets suppose i have string
var string = "$-20455.00"
I am trying to swap first two characters of a string. I was thinking to split it and make an array and then replacing it, but is there any other way? Also, I am not clear how can I achieve it using arrays? if I have to use arrays.
var string = "-$20455.00"
How can I achieve this?
You can use the replace function in Javascript.
var string = "$-20455.00"
string = string.replace(/^.{2}/g, 'rr');
Here is jsfiddle: https://jsfiddle.net/aoytdh7m/33/
You dont have to use arrays. Just do this
string[1] + string[0] + string.slice(2)
You can split to an array, and then reverse the first two characters and join the pieces together again
var string = "$-20455.00";
var arr = string.split('');
var result = arr.slice(0,2).reverse().concat(arr.slice(2)).join('');
document.body.innerHTML = result;
try using the "slice" method and string concatenation:
stringpart1 = '' //fill in whatever you want to replace the first two characters of the first string with here
string2 = stringpart1 + string.slice(1)
edit: I now see what you meant by "swap". I thought you meant "swap in something else". Vlad's answer is best to just switch the first and the second character.
Note that string[0] refers to the first character in the string, and string[1] to the second character, and so on, because code starts counting at 0.
var string = "$-20455.00";
// Reverse first two characters
var reverse = string.slice(0,2).split('').reverse().join('');
// Concat again with renaming string
var result= reverse.concat(string.slice(2));
document.body.innerHTML = result;
let finalStr = string[1] + string[0] + string.slice(2); //this will give you the result

Convert string with commas to array

How can I convert a string to a JavaScript array?
Look at the code:
var string = "0,1";
var array = [string];
alert(array[0]);
In this case alert shows 0,1. If it where an array, it would show 0. And if alert(array[1]) is called, it should pop-up 1
Is there any chance to convert such string into a JavaScript array?
For simple array members like that, you can use JSON.parse.
var array = JSON.parse("[" + string + "]");
This gives you an Array of numbers.
[0, 1]
If you use .split(), you'll end up with an Array of strings.
["0", "1"]
Just be aware that JSON.parse will limit you to the supported data types. If you need values like undefined or functions, you'd need to use eval(), or a JavaScript parser.
If you want to use .split(), but you also want an Array of Numbers, you could use Array.prototype.map, though you'd need to shim it for IE8 and lower or just write a traditional loop.
var array = string.split(",").map(Number);
Split it on the , character;
var string = "0,1";
var array = string.split(",");
alert(array[0]);
This is easily achieved in ES6;
You can convert strings to Arrays with Array.from('string');
Array.from("01")
will console.log
['0', '1']
Which is exactly what you're looking for.
If the string is already in list format, you can use the JSON.parse:
var a = "['a', 'b', 'c']";
a = a.replace(/'/g, '"');
a = JSON.parse(a);
Convert all type of strings
var array = (new Function("return [" + str+ "];")());
var string = "0,1";
var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';
var stringArray = (new Function("return [" + string+ "];")());
var objectStringArray = (new Function("return [" + objectstring+ "];")());
JSFiddle https://jsfiddle.net/7ne9L4Lj/1/
Result in console
Some practice doesnt support object strings
- JSON.parse("[" + string + "]"); // throw error
- string.split(",")
// unexpected result
["{Name:"Tshirt"", " CatGroupName:"Clothes"", " Gender:"male-female"}", " {Name:"Dress"", " CatGroupName:"Clothes"", " Gender:"female"}", " {Name:"Belt"", " CatGroupName:"Leather"", " Gender:"child"}"]
For simple array members like that, you can use JSON.parse.
var listValues = "[{\"ComplianceTaskID\":75305,\"RequirementTypeID\":4,\"MissedRequirement\":\"Initial Photo Upload NRP\",\"TimeOverdueInMinutes\":null}]";
var array = JSON.parse("[" + listValues + "]");
This gives you an Array of numbers.
now you variable value is like array.length=1
Value output
array[0].ComplianceTaskID
array[0].RequirementTypeID
array[0].MissedRequirement
array[0].TimeOverdueInMinutes
You can use split
Reference:
http://www.w3schools.com/jsref/jsref_split.asp
"0,1".split(',')
Another option using the ES6 is using Spread syntax.
var convertedArray = [..."01234"];
var stringToConvert = "012";
var convertedArray = [...stringToConvert];
console.log(convertedArray);
use the built-in map function with an anonymous function, like so:
string.split(',').map(function(n) {return Number(n);});
[edit] here's how you would use it
var string = "0,1";
var array = string.split(',').map(function(n) {
return Number(n);
});
alert( array[0] );
How to Convert Comma Separated String into an Array in JavaScript?
var string = 'hello, world, test, test2, rummy, words';
var arr = string.split(', '); // split string on comma space
console.log( arr );
//Output
["hello", "world", "test", "test2", "rummy", "words"]
For More Examples of convert string to array in javascript using the below ways:
Split() – No Separator:
Split() – Empty String Separator:
Split() – Separator at Beginning/End:
Regular Expression Separator:
Capturing Parentheses:
Split() with Limit Argument
check out this link
==> https://www.tutsmake.com/javascript-convert-string-to-array-javascript/
You can use javascript Spread Syntax to convert string to an array. In the solution below, I remove the comma then convert the string to an array.
var string = "0,1"
var array = [...string.replace(',', '')]
console.log(array[0])
I remove the characters '[',']' and do an split with ','
let array = stringObject.replace('[','').replace(']','').split(",").map(String);
More "Try it Yourself" examples below.
Definition and Usage
The split() method is used to split a string into an array of substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is split between each character.
Note: The split() method does not change the original string.
var res = str.split(",");
Regexp
As more powerful alternative to split, you can use match
"0,1".match(/\d+/g)
let a = "0,1".match(/\d+/g)
console.log(a);
Split (",") can convert Strings with commas into a String array, here is my code snippet.
var input ='Hybrid App, Phone-Gap, Apache Cordova, HTML5, JavaScript, BootStrap, JQuery, CSS3, Android Wear API'
var output = input.split(",");
console.log(output);
["Hybrid App", " Phone-Gap", " Apache Cordova", " HTML5", "
JavaScript", " BootStrap", " JQuery", " CSS3", " Android Wear API"]
var i = "[{a:1,b:2}]",
j = i.replace(/([a-zA-Z0-9]+?):/g, '"$1":').replace(/'/g,'"'),
k = JSON.parse(j);
console.log(k)
// => declaring regular expression
[a-zA-Z0-9] => match all a-z, A-Z, 0-9
(): => group all matched elements
$1 => replacement string refers to the first match group in the regex.
g => global flag
Why don't you do replace , comma and split('') the string like this which will result into ['0', '1'], furthermore, you could wrap the result into parseInt() to transform element into integer type.
it('convert string to array', function () {
expect('0,1'.replace(',', '').split('')).toEqual(['0','1'])
});
Example using Array.filter:
var str = 'a,b,hi,ma,n,yu';
var strArr = Array.prototype.filter.call(str, eachChar => eachChar !== ',');

Categories

Resources