I have a number which I needed to format as currency, to do this im having to turn my number into a string and run a function, This is working but its showing to X decimal places, Is it possible to use 'toFixed' on a string at all? I've tried with no luck and im unsure how to turn the string back into a number, I've used parseInt only it stops at the first character as it doesnt read past my delimeter...
var amount = String(EstimatedTotal);
var delimiter = ","; // replace comma if desired
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
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);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
at the moment the amount variable showing as 1,234,567.890123
Thanks for the help all ,
Managed to get it working with this
amount = String(EstimatedTotal)
amount += '';
x = amount.split('.');
x1 = x[0];
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
num=x1 ;
Not sure what you mean by currency-
this adds commas for thousands separators and forces two decimal places
input can be a string of digits with or without commas, minus sign and decimal, or a number
function addCommas2decimals(n){
n= Number(String(n).replace(/[^-+.\d]+/g, ''));
if(isNaN(n)){
throw new Error('Input must be a number');
}
n= n.toFixed(2);
var rx= /(\d+)(\d{3})/;
return n.replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
var s= '1234567.890123'
addCommas2decimals(s)
/* returned value: (String)
1,234,567.89
*/
I recommend the "number_format" function from the phpjs project:
http://phpjs.org/functions/number_format:481
Usage:
amount = number_format(EstimatedTotal, 2, '.', ',');
Just like the PHP function... http://php.net/manual/en/function.number-format.php
Related
var n = "reversestrings", k=3;
want to reverse string in chunk of 'k',
Answer would be : ver sre tse nir gs;
if Last word less then 'k' then don't need to reverse.
I am using below code but not getting expected answer.
var n = 'stringreverses', k = 3, str = '', s = '';
var c = 0;
for( var i=0; i<n.length; i++ ){
if( c<k ){
c++
str += n[i];
s=str.split('').reverse().join('');
}
else{
console.log("-" + s);
c=0;
}
}
First we need to split input to chunks with the same size (the last one can be smaller), next we reverse every chunk and concatenate at the end.
var input = "123456",
chunks = input.match(new RegExp('.{1,' + k + '}', 'g'));
var result = chunks.map(function(chunk) {
return chunk.split('').reverse().join('');
}).join('');
Homework or not, here is a good use case to start with strings.
Here is a C approach but you have more in Javascript.
In fact you want to reverse by chunk so deal with chunk. How to create a chunk of string ? a way is to use slice https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/slice
var str = "abcdef";
console.log(str.slice(0,2));
So you have an easy way to slice your string into chunk.
Then you have to iterate over it, there is no good way of doing it actually there is dozen but you could do it from backward to the beginning of the string:
for( i=str.length ; i>0 ; i -= k ){
// i will go from the end of your str to
// the beginning by step of k(=3) and you can use i - k and i
// to slice your string (as we see it before)
// you have to take care of the last part that could be less than
// 3
}
then you have to format the result, the most easy way to do that is to concatenate results into a string here it is :
var strRes = "";
strRes += "res 1";
strRes += "res 2";
console.log(strRes); // should screen "res 1res 2"
As it is homework, I wont make a jsfiddle, you have here all the pieces and it's up to you to build the puzzle.
hope that help
$(function() {
var n = 'reversestrings', k = 3;
var revString = "";
for (var i =0; i<=n.length; i++) {
if (i%k == 0) {
l = parseInt(k) + parseInt(i);
var strChunk = n.substring(i,l);
var innerStr = "";
for (var j =0; j<strChunk.length; j++) {
var opp = parseInt(strChunk.length) - parseInt(j) - 1;
innerStr = innerStr + strChunk.charAt(opp);
}
revString = revString + " "+innerStr;
}
}
alert(revString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
My take on this. Pure JS without even built-in functions:
function reverseSubStr(str) {
var right = str.length - 1, reversedSubStr = '';
while(right >= 0) {
reversedSubStr += str[right];
right--;
}
return reversedSubStr;
}
function reverseStr(str) {
var initialStr = str, newstr = '', k = 3, substr = ''
for(var i = 1; i <= initialStr.length; i++) {
substr += initialStr[i - 1]; // form a substring
if(i % k == 0) { // once there are 3 symbols - reverse the substring
newstr += reverseSubStr(substr) + " "; // ... and add space
substr = ''; // then clean temp var
}
}
return newstr += substr; // add the remainder of the string - 'gs' - and return the result
}
var str = 'reversestrings';
console.log(reverseStr(str)); //ver sre tse nir gs
I like #Jozef 's approch but here is mine as well for those who are not much into Regex -
//Taking care of Tail Calling
function reverStrInChunk(str, k, r=''){
let index=0, revStr,
res = str.substring(index, k), remStr;
revStr = res.split("").reverse().join("");
remStr = str.substring(k, str.length);
r = r + revStr;
if(remStr.length>k){
return reverStrInChunk(remStr,k, r+" ");
}
else if(remStr.length<k) {
return r +" "+remStr;
}else{
return r +" "+ remStr.split("").reverse().join("");
}
}
var aStr = reverStrInChunk('reversestrings',3);//ver sre tse nir gs
console.log(aStr);
I am trying to divide my string in 2 lines if string is greater than 15 characters, so i am finding a space after 15 char and putting /n to string so that when var gets printed it should get printed in 2 lines.
following is my JavaScript code. its not working, please if anyone can help.
Thankyou
var name = row.product_name;
var val = 15;
var output;
var flag = false;
console.log(name[0]);
for(i=0; i<row.product_name.length; i++)
{
if(i > val)
{
if(name[i] == ' ')
{
name[i] = "/n";
flag = true;
}
}
if(flag)
{
val = val + 15;
flag = false;
}
}
this can't work because javascript strings are immutable, so you can't reassign name[i]. You have to use replace, slice, split, or other operations on the whole string
var myString = "jsdjposjgiohg squg oiq oih osqdh uh hsquv hup h opsdqh voph";
myStringA=myString.split(" ");
var newString="";
var n=0;
for (var i=0;i<myStringA.length;i++){
n+=myStringA[i].length;
if (n>15){
n=0;
newString+=myStringA[i]+"\n";
}else{
newString+=myStringA[i]+" ";
}
}
console.log(newString);
Strings are immutable in javascript so you need to put the changes in a new variable
Also the newline character is \n not /n
var name = row.product_name;
var val = 15;
var output = "";
var flag = false;
console.log(name[0]);
for(i=0; i<row.product_name.length; i++)
{
output += name[i]
if(i > val)
{
if(name[i] == ' ')
{
output[i] = "\n";
flag = true;
}
}
if(flag)
{
val = val + 15;
flag = false;
}
}
I have two string which should be put together into one string. First string is a input value and second string is a pattern how the first string should look. Here is the example - Input string( var val ) - 9165678823 Patter string( var mask ) - (999)999-9999 Output string should look like( var startVal ) - (916)567-8823 I have tried working out and this is my code
var val = $(control).data("loadMaskValue"); // Input Value
var mask = $(control).attr("mask"); //Masking Pattern
var startVal = "";
var j = 0;
for (var i = 0; i < mask.length; i++) {
var c = mask.charAt(j);
if (c == '9' || c == 'X' || c == 'A') { //Checks the char is normal char
startVal += val.charAt(j);
}
else {
startVal += c; //Inserts the special char to string like ( ) -
startVal += val.charAt(j);
}
j = startVal.length;
}
The problem with this code is it misses one number in between. The result of this code is startValue - (965)688-2. PLease help me.
Here's a slightly simpler implementation:
var input = '9165678823';
var mask = '(999)999-9999';
var output = '';
var offset = 0;
for (var i = 0; i < mask.length; i++) {
var char = mask.charAt(i);
if ('9XA'.indexOf(char) != -1) {
output += input.charAt(i - offset);
} else {
output += mask.charAt(i);
offset += 1;
}
}
console.log(output);
Make sure that input has been stripped of all whitespace at the beginning and end.
Demo: http://jsfiddle.net/qWtjk/
You can use a regular expression to take the elements out. Check the fiddle: http://jsfiddle.net/BuddhiP/9MmqS/
var str= '9165678823';
var regEx = new RegExp("(\d{3})(\d{3})(\d{4})");
var m = regEx.exec(str);
var res = '(' + m[1] + ')' + m[2] + '-' + m[3];
console.log(res);
result is (916)567-8823
UPDATE: How to make this work with a dynamic pattern. Check updated fiddle: http://jsfiddle.net/BuddhiP/9MmqS/
$(function() {
var str= '9165678823';
var regEx = new RegExp("(\\d{3})(\\d{3})(\\d{4})");
var m = regEx.exec(str);
var mask = "({0}){1}-{2}";
var res = mask.supplant(m.slice(1));
console.log(res);
});
Using supplant method from here: http://javascript.crockford.com/remedial.html
Once you understand your regular expression, you can make this work with any pattern and mask.
How do I break up a string every X amount of characters? For example, I'd like to break up a very long string every 1000 characters, and the string could be completely random everytime.
var string = <my text string that is thousands of characters long>
You could use Regex:
'asdfasdfasdfasdf'.match(/.{3}|.{1,2}/g); // 'asd', 'fas', etc.
Replace 3 with 1000 of course.
Here's a contrived example: http://jsfiddle.net/ReRPz/1/
As a function:
function splitInto(str, len) {
var regex = new RegExp('.{' + len + '}|.{1,' + Number(len-1) + '}', 'g');
return str.match(regex );
}
That RegExp really only needs to be created once if you have a set number to split like 1000.
Try this function:
function getParts(str, len)
{
var res = [];
while (str.length) {
res.push(str.substring(0, len));
str = str.substring(len);
}
return res;
}
var s = "qweasedzxcqweasdxzc12";
console.log(getParts(s, 10));
i would use substring function on string
str = //the given string
arr = [];
for(i=0;i<str.length;i+=1000)
{
s = i;
// if the last string is less than 1000chars
e = (str.length - i) > 1000 ? (i+1000) : (str.length - i);
arr.push = str.substring(s,e);
}
Here's a way to do it recursively:
var string = "my text string that is thousands of characters long";
var arr = [];
function div( str, len ) {
if( str.length < len )
return arr.push(str);
else
arr.push(str.substring(0,len))
div( str.substring(len), len );
}
div( string, 5 );
for( var i = 0; i < arr.length; i++ ) {
document.write( arr[i] + "<br/>");
}
/* output:
my te
xt st
ring
that
is th
ousan
ds of
char
acter
s lon
g
*/
Like this:
var myString = "my text string that is thousands of characters long";
var myCurrentString = "";
var myBrokenUpString = new Array();
for(var i = 0; i < myString.length; i++) {
myCurrentString += myString.charAt(i);
if(i % 1000 == 0) {
myBrokenUpString.push(myCurrentString);
myCurrentString = "";
}
if(i + 1 == myString.length) myBrokenUpString.push(myCurrentString);
}
Please note that the above code is untested and may contain errors.
You can then POST the array and piece it back together on the other end. The piecing-together-code would look something like this:
var myRestoredString = "";
for(var i = 0; i<myBrokenUpString.length; i++) {
myRestoredString += myBrokenUpString[i];
}
Borrowing the idea from Joe Tuskan:
var str = 'asdfasdfasdfasdf';
var len = 3;
var regex = new RegExp(".{"+len+"}", "g");
var trail = str.length - (str.length % len);
var parts = str.match(regex);
parts.push(str.substring(trail));
document.write(parts.join('<br>'));
http://jsfiddle.net/6aSHB/1/
I have array of 32 bit integers in javascript.
How to convert it into the Hex string
and again build the same 32 bit integer array from that Hex string when required?
hexString = yourNumber.toString(16);
can be used to convert number to hex
but when array of numbers is converted into Hex string (it will be continuous or separated by some character) then how do I get back array of numbers from that string?
If you want to do it without commas
[3546,-24,99999,3322] ==> "00000ddaffffffe80001869f00000cfa"
then you can build up the string using 8 hex-digits for each number. Of course, you'll have to zero-pad numbers that are shorter than 8 hex-digits. And you'll have to ensure that the numbers are encoded with twos-compliment to properly handle any negative values.
Here's how to do that:
var a = [3546,-24,99999,3322];
alert("Original is " + JSON.stringify(a)); // [3546,-24,99999,3322]
// convert to hex string...
//
var b = a.map(function (x) {
x = x + 0xFFFFFFFF + 1; // twos complement
x = x.toString(16); // to hex
x = ("00000000"+x).substr(-8); // zero-pad to 8-digits
return x
}).join('');
alert("Hex string " + b); // 00000ddaffffffe80001869f00000cfa
// convert from hex string back to array of ints
//
c = [];
while( b.length ) {
var x = b.substr(0,8);
x = parseInt(x,16); // hex string to int
x = (x + 0xFFFFFFFF + 1) & 0xFFFFFFFF; // twos complement
c.push(x);
b = b.substr(8);
}
alert("Converted back: " + JSON.stringify(c)); // [3546,-24,99999,3322]
here's a jsFiddle that shows the above example.
Here you go:
var a = [3546,-24,99999,3322];
alert("Original is " + JSON.stringify(a));
var b = (a.map(function (x) {return x.toString(16);})).toString();
alert("Hex string " + b);
var c = b.split(",").map(function (x) {return parseInt(x, 16);});
alert("Converted back: " + JSON.stringify(c));
http://jsfiddle.net/whT2m/
ADDENDUM
The OP asked about using a separator other than a comma. Only a small tweak is needed. Here is a version using the semicolon:
var a = [3546,-24,99999,3322];
alert("Original is " + JSON.stringify(a));
var b = (a.map(function (x) {return x.toString(16);})).join(";");
alert("Hex string " + b);
var c = b.split(";").map(function (x) {return parseInt(x, 16);});
alert("Converted back: " + JSON.stringify(c));
http://jsfiddle.net/DEbUs/
var ints = [1,2,30,400];
var hexstr = "";
for(var i=0; i < ints.length; i++) {
hexstr += ints[i].toString(16) + ";";
}
document.write("Hex: " + hexstr + "<br>");
var intsback = new Array();
var hexarr = hexstr.split(";");
for(var i = 0; i < hexarr.length-1; i++) {
intsback.push(parseInt(hexarr[i], 16));
}
document.write("Integers back: " + intsback);
http://jsfiddle.net/YVdqY/
Here are two functions to do the conversions using plain javascript that should work in all browsers:
var nums = [3456, 349202, 0, 15, -4567];
function convertNumArrayToHexString(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
result.push(list[i].toString(16));
}
return(result.join(","));
}
function convertHexStringToNumArray(str) {
var result = [];
var list = str.split(/\s*,\s*/);
for (var i = 0; i < list.length; i++) {
result.push(parseInt(list[i], 16));
}
return(result);
}
var temp = convertNumArrayToHexString(nums);
temp = convertHexStringToNumArray(temp);
And, a working demo: http://jsfiddle.net/jfriend00/3vmNs/
Hex string to integer array(ex, 0E0006006200980000000000000000)
dataToNumberArr(data) {
if(data.length == 2) {
let val = parseInt(data, 16);
return [val];
} else if(data.length > 2) {
return dataToNumberArr(data.substr(0, 2)).concat(dataToNumberArr(data.substr(2)));
}
}
Use this:
parseInt(hexstr, 16);
Source: http://javascript.about.com/library/blh2d.htm
You can call parseInt(hexString, 16) to convert a hex string to an integer value.