convert js number to xxx xxx xxx ,xx? - javascript

I have an number I want convert its format to xxx xxx xxx,xx(will use for display in html page)
Example
1069.83
to
1 069,83
OR something like this
13761000.00
to
13 761 000,00
In JavaScript are the build-in function or the ways to do this?

If this is your data pattern you can enhance this function: ( see it here : http://jsfiddle.net/DSJuL/1/ )
var number = 13761000.00;
alert(formatNum(number));
function formatNum(number)
{
var newNum = "";
var oldNumStr = number + "";
var done = 0;
var parts = oldNumStr.split(".");
var newPart1 = "";
var newPart2 = parts[1];
for(var j= parts[0].length -1 ;j >= 0;j--)
{
newNum = parts[0][j] + newNum;
done++;
if((done%3) == 0)
newNum = " " + newNum;
}
newNum = (newPart2)? (newNum + "," + newPart2) : newNum + ",00" ;
return newNum;
}

If using jQuery is an option you can check the globalization plugin. It supports number formatting nicely. Check this out.
If you can't use jQuery - check this.

Related

how can i make all the filenames the same length by adding spaces to it?

i want to make the filename+spaces=211 characters
but the problem is that if the file name characters = 30
i would need 181 spaces
while if file name characters = 80
i would need 131 spaces
i have tried advanced renamer
tags options + spaces .
<Name>
..
and even this script in the scripts section
var maxLength = 25;
var name = item.name;
var date = app.parseTags("<Year Modified><Month Modified><Day Modified>");
var numSpaces = maxLength - name.length - date.length;
var spaces = "";
for (i = 0; i < numSpaces; i++) spaces += " ";
return name + spaces + date;
but it give me this error
name is not defined in the line 3
the script that works using advanced Renamer
var maxLength = 222;
var name = item.name;
var date = app.parseTags("<Year Modified><Month Modified><Day Modified>");
var numSpaces = maxLength - name.length - date.length;
var spaces = "";
for (i = 0; i < numSpaces; i++) spaces += " ";
return name + spaces + date;
credits David Lee from advanced Renamer forms
You could use String#padEnd(), to add whitespaces to the end of your filename strings so that the resulting string has a minimum length a specified by you.
Consider the snippet below until where fileNameA.padEnd(211) returns a new string with the same leading characters as fileNameA, but with whitespaces padding the remainder of the string such that the string has length 211:
const fileNameA = 'your file name';
const fileNameB = 'some other big file name';
const paddedFileNameA = fileNameA.padEnd(211);
const paddedFileNameB = fileNameB.padEnd(211);
console.log(`
paddedFileNameA:
"${paddedFileNameA}"
length of paddedFileNameA: ${paddedFileNameA.length}
`)
console.log(`
paddedFileNameB:
"${paddedFileNameB}"
length of paddedFileNameB: ${paddedFileNameB.length}
`)
Update
I'm not familiar with the scripting feature set in Advanced Renamer, however you might find this works for you:
/*
Set length to 211
*/
var maxLength = 211;
var name = item ? item.name : '';
var date = app.parseTags("<Year Modified><Month Modified><Day Modified>");
/*
Ensure variables are not undefined or null
*/
if(!name) {
name = '';
}
if(!date) {
date = '';
}
/*
Construct result string
*/
var result = name;
for (i = 0; i < (maxLength - (name.length + date.length)); i++) {
result += ' ';
}
result += date;
return result;

I trying to convert a string to output looking a certain way using the replace but having issues

I'm trying to convert a string to output looking a certain way and I figured the best way to do it was using pattern matching but I'm running into some issues. I don't want to break the string down and then concatenated it. I was hoping there was a simpler way. I'm also having an issue with (id) it seems that the string literal after (id,)lastname is taking on the replacement value
var myFunction - function(){
var str = "id,created,employee(id,firstname,employeeType(id), lastname),location";
var str2="id, created, employee";
var str3 = "(id,firstname,employeeType";
var str4="(id)";
var str5 ="lastname)";
var str6 = "location";
var test = str2.replace(/[,]/g, '<br>\r\n').split(",");
var test1 = str3.replace(/[(/,]/g, '<br>-\r\n').split(",");
var test2 =str4.replace(/[()/,]/g, '<br />--\r\n').split(",");
var test3 = str5.replace(/[,/)]/g, '<br />').split(",");
var test4 = str6.replace(/[)/,]/g, '<br />').split(",");
var result =test + test1 + test2 + test3 + test4 ;
var match = result.split(',')
document.getElementById("myDemo").innerHTML = match.join("<br />");;
}
myFunction()
My output looks like below
id
created
employee
- id
- firstname
- employeeType
-- id
-- lastname this should only be one dash not two
location
what am I doing wrong?
Here is a way that walks through the string one character as a time. When either ( or ) are encountered, a counter is incremented or decremented that indicates how many preceding - characters there should be.
var stringFormatter = function() {
var str = "id,created,employee(id,firstname,employeeType(id), lastname),location";
var formatted = '';
var indentCount = 0;
var chars = str.split('');
chars.forEach(function(char) {
if (char == '(') {
indentCount++;
} else if (char == ')') {
indentCount--;
}
if (char == ',' || char == '(') {
formatted = formatted.concat('<br/>');
for (var i = 0; i < indentCount; i++ ) {
formatted = formatted.concat('-');
}
} else if (char != '(' && char != ')') {
formatted = formatted.concat(char);
}
});
document.getElementById("myDemo").innerHTML = formatted;
}
stringFormatter();
The output looks like:
id
created
employee
-id
-firstname
-employeeType
--id
- lastname
location
For any nesting level you can use this
var myFunction = function(){
var str = "id,created,employee(id,firstname,employeeType(id), lastname),location";
while(/\([^()]+\)/g.test(str))
{
m = /\(([^()]+)\)/g.exec(str);
m[1] = m[1].replace(/(-+)/g,"-$1");
m[1] = m[1].replace(/,/g,"-");
str = str.replace(/\(([^()]+)\)/,'-'+m[1]);
}
str = str.replace(/,/g,'<br>\r\n');
str = str.replace(/(-+)/g,'<br>$1 \r\n');
document.getElementById("myDemo").innerHTML += str + '</br>';
}
myFunction();
Output:
id
created
employee
- id
- firstname
- employeeType
-- id
- lastname
location
See the result for more nesting level
var str = "id,created,employee(id,firstname,contact(Mobile,Landline(home,office)),employeeType(id), lastname),location";
...
Output:
id
created
employee
- id
- firstname
- contact
-- Mobile
-- Landline
--- home
--- office
- employeeType
-- id
- lastname
location

How to concatenate/change the error message if the input is not a valid date in js?

I tried this for almost two days but still nothing. Maybe someone can help who is highly skilled in javascript loops.
I asked this question before and change some code but still no luck in showing the expected data. And still struggling for this.
I have this code:
$(function(){
var len = $('#groupContainer > div').length;
var data = [];
for(var i=0; i < len; i++){
var number = $('#number_' + [i + 1]);
var date = $('#date_' + [i + 1]);
var count = i + 1;
var message ="";
var a = number.map(function(){
return this.value;
});
var b = date.map(function(){
return this.value;
});
var newObj = {number: a[0], date: b[0]}
data.push(newObj);
}
var message = "";
for(var c = 0; c < data.length; c++)
{
haveErrorInGroup = false;
for(var d in data[c])
{
if(data[c].hasOwnProperty(d))
{
if(data[c][d] == "")
{
if(!haveErrorInGroup){
haveErrorInGroup= true;
message += 'Group: ' + [c + 1] + '\n';
}
message += d + ' is required!\n';
}
if(d == "date")
{
if(data[c][d].length != 22 && data[c][d] != "")
{
message += 'Invalid Date!\n';
}
}
}
}
}
if(message){
alert(message);
}
});
And the expected output:
If all the fields in group 1 is filled and group 2 is not show alertbox:
Group 2:
Number is required!
Date is required!
If all field is not filled show:
Group 1, 2 Number is required!
Group 1, 2 Date is required!
And if date is not really a date:
Group 1, 2 Date is invalid.
And if one of the inputs is invalid.
Group 2 Date is invalid.
If all field is filled do nothing.
Here's my FIDDLE
I think you are looking for something like jquery-validate. I'm pretty sure it comes with a native date validator but if you want to have a more specific format you can just put a regex into it.

Javascript slice from reverse

I want to slice the javascript variable in the given condition.
The condition is if the variable is of length 12 it should slice as 2,6,4 and if it is of length 11 it should slice as 2,5,4. How can i slice this.
Here is what i have tried.
Code :
var new_no = "("+phone_no.slice(0,2)+")-"+phone_no.slice(2,7)+"-"+phone_no.slice(7,11);
How can i make the length checking condition and slice according to my given condition ?
You can make the middle slice conditional:
var midEnd = phone_no.length == 11? 7 : 8;
var new_no = "("+phone_no.slice(0,2)+")-"+phone_no.slice(2,midEnd)+"-"+phone_no.slice(midEnd);
If you don't supply a second parameter, it will slice to the end. Though for greater browser compatibility I'd use substr instead:
var new_no = '(' + phone_no.substr(0,2) + ')-' +
phone_no.substr(2,midEnd) +
'-' + phone_no.substr(midEnd);
function preparePhoneNo(num) {
return '(' + num.slice(0, 2) + ')-' + num.slice(2, -4) + '-' + num.slice(-4);
}
var phone_no = "123465789012";
var new_no = preparePhoneNo(phone_no);
Here is my take, I would use substr
var phone_no = '12345678901';
var midGroup = phone_no.length == 11 ? 5 : 6;
var new_no = "("+phone_no.substr(0,2)+")-"+phone_no.substr(2,midGroup)+"-"+phone_no.substr(midGroup + 2);
alert(new_no);
You can simply use .length to check the length of the number and then two simple conditions will do the trick:
var phone_no = "123456789878";
if(phone_no.length === 11)
var new_no = "("+phone_no.slice(0,2)+")-"+phone_no.slice(2,7)+"-"+phone_no.slice(7,11);
else if(phone_no.length === 12)
var new_no = "("+phone_no.slice(0,2)+")-"+phone_no.slice(2,8)+"-"+phone_no.slice(8,12);
else
alert('Invalid Number');
See the DEMO here

Javascript multiple digit index

I have searched around the net and the solution must be so simple no one has asked?
I just wanted to use an index like + i + to return 001, 002, 003, etc
How about
('000' + i).substr(-3);
So something like this?
function number_pad(num,len) {
num = ""+num;
while(num.length < len) num = "0"+num;
return num;
}
// Usage: number_pad(i,3);
Alternatively, extend the native object:
Number.prototype.pad(len) {
var num = ""+this;
while(num.length < len) num = "0"+num;
return num;
}
// Usage: i.pad(3);
For future reference, this is called zerofill or zero-padding.
function paddedNumber(n) {
// A string containing the fully padded zero value.
var zeroes = "000";
// The number as a string.
var numstr = "" + n;
var nDigits = numstr.length;
// Keep any sign at the front.
var sign = "";
if (/^[\+\-]/.test(numstr)) {
sign = numstr.charAt(0);
numstr = numstr.substring(1);
}
// Concatenates the number with just enough zeroes.
// No padding if itoa is already longer than the pad.
return sign + zeroes.substring(nDigits) + numstr;
}

Categories

Resources