I am working on a project where I require to format incoming numbers in the following way:
###.###
However I noticed some results I didn't expect.
The following works in the sense that I don't get an error:
console.log(07);
// or in my case:
console.log(007);
Of course, it will not retain the '00' in the value itself, since that value is effectively 7.
The same goes for the following:
console.log(7.0);
// or in my case:
console.log(7.000);
JavaScript understands what I am doing, but in the end the actual value will be 7, which can be proven with the following:
const leadingValue = 007;
const trailingValue = 7.00;
console.log(leadingValue, trailingValue); // both are exactly 7
But what I find curious is the following: the moment I combine these two I get a syntax error:
// but not this:
console.log(007.000);
1) Can someone explain why this isn't working?
I'm trying to find a solution to store numbers/floats with the exact precision without using string.
2) Is there any way in JS/NodeJS or even TypeScript to do this without using strings?
What I currently want to do is to receive the input, scan for the format and store that as a separate property and then parse the incoming value since parseInt('007.000') does work. And when the user wants to get this value return it back to the user... in a string.. unfortunately.
1) 007.000 is a syntax error because 007 is an octal integer literal, to which you're then appending a floating point part. (Try console.log(010). This prints 8.)
2) Here's how you can achieve your formatting using Intl.NumberFormat...
var myformat = new Intl.NumberFormat('en-US', {
minimumIntegerDigits: 3,
minimumFractionDigits: 3
});
console.log(myformat.format(7)); // prints 007.000
Hi
You can use an aproach that uses string funtions .split .padStart and .padEnd
Search on MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
Here you have an example:
const x = 12.1;
function formatNumber( unformatedNumber) {
const desiredDecimalPad = 3;
const desiredNonDecimalPad = 3;
const unformatedNumberString = unformatedNumber.toString();
const unformatedNumberArr = unformatedNumberString.split('.');
const decimalStartPadded = unformatedNumberArr[0].padStart(desiredDecimalPad, '0');
const nonDecimalEndPadded = unformatedNumberArr[1].padEnd(desiredNonDecimalPad, '0');
const formatedNumberString = decimalStartPadded + '.' + nonDecimalEndPadded;
return formatedNumberString;
}
console.log(formatNumber(x))
Related
So I have got a column and i want to get the first 3 digits only from it and store them in a function called wnS using the split function or any other method that would work. I want to get the first three digits before "_"
I tried doing this but it didn't work, and I also kept getting "TypeError: wnC.split is not a function"
var ssh = ssPO.getSheetByName("PO for OR (East).csv")
wnC = ssh.getRange("N2:N");
var wnS = wnC.split("_");
I would really appreciate an answer
If you need more info please let me know
Thank you.
After you define range, you have to get the values.
function first_3_digs (){
var ssh = ssPO.getSheetByName("PO for OR (East).csv")
var wnC = ssh.getRange("N2:N");
var values = wnC.getValues();
const first_3_digs = values.filter(r => {
if(r.toString().includes('_')){return r;}
}).map(r=> r.toString().split('_')[0]);
console.log(first_3_digs)
}
const cell = "(303) 987-4567";
const first3 = cell.match(/\d{3}/)[0];
//result:303
String method match()
regular expression
BTW: you can test methods like this very easily in the console.log in the browsers developer tools.
am trying to replace numbers in an array but am facing an issue which am not really able to correctly manage regarding how to correctly target the just one data I really have to change.
I'll make an example to have more accuracy on describing it.
Imagine my data array look like that:
["data", "phone numbers", "address"]
I can change numbers via following script but my first problem is that it makes no differences between the number it find in columns, for example "phone numbers" from "address" (at the moment am not using it, but should I include a ZIP code in the address it would be really be a problem)
Beside, my second and current problem with my script, is that obviosuly in the same "phone numnbers" a number may appear more times while I'd like to affect only the first block of the data - let's say to add/remove the country code (or even replace it with it's country vexillum) which I normally have like that "+1 0000000000" or "+54 0000000000"
So if a number is for example located in EU it really make this script useless: Spain is using "+34" while France "+33" and it wouldn't succeded in any case becouse it recognize only "+3" for both.
I've found some one else already facing this problems which seems to solved it wrapping the values inside a buondaries - for example like that "\b"constant"\b" - but either am wronging syntax either it does not really apply to my case. Others suggest to use forEach or Array.prototype.every which I failed to understand how to apply at this case.
Should you have other ideas about that am open to try it!
function phoneUPDATES(val)
{
var i= 0;
var array3 = val.value.split("\n");
for ( i = 0; i < array3.length; ++i) {
array3[i] = "+" + array3[i];
}
var arrayLINES = array3.join("\n");
const zero = "0";
const replaceZERO = "0";
const one = "1";
const replaceONE = "1";
const result0 = arrayLINES.replaceAll(zero, replaceZERO);
const result1 = result0.replaceAll(one, replaceONE);
const result2 = result1.replaceAll(two, replaceTWO);
const result3 = result2.replaceAll(thre, replaceTHREE);
const result4 = result3.replaceAll(four, replaceFOUR);
const result5 = result4.replaceAll(five, replaceFIVE);
const result6 = result5.replaceAll(six, replaceSIX);
const result7 = result6.replaceAll(seven, replaceSEVEN);
const result8 = result7.replaceAll(eight, replaceEIGHT);
const result9 = result8.replaceAll(nine, replaceNINE);
const result10 = result9.replaceAll(ten, replaceTEN);
const result11 = result10.replaceAll(eleven, replaceELEVEN);
Why not use a regex replace, you could do something like /(\+\d+ )/g which will find a + followed by one or more digits followed by a space, and then you can strip out the match:
const phoneNumbers = [, "+54 9876543210"]
console.log(phoneNumbers.map((num) => num.replaceAll(/(\+\d+ )/g, '')))
If you need to only target the second element in an array, i'd imagine your data looks like
const data = [["data", "+1 1234567890, +1 5555555555", "address"], ["data", "+11 111111111, +23 23232323", "address"]];
console.log(data.map((el) => {
el[1] = el[1].replaceAll(/(\+\d+ )/g, '');
return el;
}))
ok, this almost is cheating but I really didn't thought it before and, by the way does, not even actually solve the problems but jsut seems to work around it.
If I call the replacemente in decreasing order that problem just does not show up becouse condition of replacement involving higher numbers are matched before the smaller one.
but should some one suggest a complete "true code comply" solution is wellcome
on dwitter.net i often see dweets that are encoded interestingly to minify the JS to character count.
for example https://www.dwitter.net/d/22372 (or https://www.dwitter.net/d/11506)
eval(unescape(escape`𮀮𩡯𫡴🐧𫐠𨐧𛁸𪑬𫁔𩑸𭀨𭐲𝠲𭀿𩀽𮀮𩱥𭁉𫑡𩱥𡁡𭁡𛀰𛁶🐳𝠬𭠩𨑴𨐊𩡯𬠨𨰮𭱩𩁴𪁼👷👩🐹𩐽𪐥𭠪𝠬𩁛𪐪𝀫🠵𪑬𫁒𩑣𭀨𦀽𩐫𩐯𤰨𭀭𪐯𭰩𛁩𛰳𛰹𪐼𭰺`.replace(/u../g,'')))
Now I understand how to decode this and read the javascript, it's pretty trivial
unescape(escape`𮀮𩡯𫡴🐧𫐠𨐧𛁸𪑬𫁔𩑸𭀨𭐲𝠲𭀿𩀽𮀮𩱥𭁉𫑡𩱥𡁡𭁡𛀰𛁶🐳𝠬𭠩𨑴𨐊𩡯𬠨𨰮𭱩𩁴𪁼👷👩🐹𩐽𪐥𭠪𝠬𩁛𪐪𝀫🠵𪑬𫁒𩑣𭀨𦀽𩐫𩐯𤰨𭀭𪐯𭰩𛁩𛰳𛰹𪐼𭰺`.replace(/u../g,''))
returns
x.font='2em a',x.fillText('\u2620 ',3,25)
t?0:d=x.getImageData(0,0,v=36,v).data
for(c.width|=w=i=936;i--;)e=i%v*6,d[i*4+3]>50||x.fillRect(X=e+e/2*S(t-i/w)+w,i/3-e*C(t-X/99)+e+50,9,i<1?w:9)
but what I don't understand is how to encode js like this.
I noticed there is an intermediary step in this process
running:
escape`𮀮𩡯𫡴🐧𫐠𨐧𛁸𪑬𫁔𩑸𭀨𭐲𝠲𭀿𩀽𮀮𩱥𭁉𫑡𩱥𡁡𭁡𛀰𛁶🐳𝠬𭠩𨑴𨐊𩡯𬠨𨰮𭱩𩁴𪁼👷👩🐹𩐽𪐥𭠪𝠬𩁛𪐪𝀫🠵𪑬𫁒𩑣𭀨𦀽𩐫𩐯𤰨𭀭𪐯𭰩𛁩𛰳𛰹𪐼𭰺`
returns
%uD878%uDC2E%uD866%uDC6F%uD86E%uDC74%uD83D%uDC27%uD832%uDC65%uD86D%uDC20%uD861%uDC27%uD82C%uDC78%uD82E%uDC66%uD869%uDC6C%uD86C%uDC54%uD865%uDC78%uD874%uDC28%uD827%uDC5C%uD875%uDC32%uD836%uDC32%uD830%uDC20%uD827%uDC2C%uD833%uDC2C%uD832%uDC35%uD829%uDC0A%uD874%uDC3F%uD830%uDC3A%uD864%uDC3D%uD878%uDC2E%uD867%uDC65%uD874%uDC49%uD86D%uDC61%uD867%uDC65%uD844%uDC61%uD874%uDC61%uD828%uDC30%uD82C%uDC30%uD82C%uDC76%uD83D%uDC33%uD836%uDC2C%uD876%uDC29%uD82E%uDC64%uD861%uDC74%uD861%uDC0A%uD866%uDC6F%uD872%uDC28%uD863%uDC2E%uD877%uDC69%uD864%uDC74%uD868%uDC7C%uD83D%uDC77%uD83D%uDC69%uD83D%uDC39%uD833%uDC36%uD83B%uDC69%uD82D%uDC2D%uD83B%uDC29%uD865%uDC3D%uD869%uDC25%uD876%uDC2A%uD836%uDC2C%uD864%uDC5B%uD869%uDC2A%uD834%uDC2B%uD833%uDC5D%uD83E%uDC35%uD830%uDC7C%uD87C%uDC78%uD82E%uDC66%uD869%uDC6C%uD86C%uDC52%uD865%uDC63%uD874%uDC28%uD858%uDC3D%uD865%uDC2B%uD865%uDC2F%uD832%uDC2A%uD853%uDC28%uD874%uDC2D%uD869%uDC2F%uD877%uDC29%uD82B%uDC77%uD82C%uDC69%uD82F%uDC33%uD82D%uDC65%uD82A%uDC43%uD828%uDC74%uD82D%uDC58%uD82F%uDC39%uD839%uDC29%uD82B%uDC65%uD82B%uDC35%uD830%uDC2C%uD839%uDC2C%uD869%uDC3C%uD831%uDC3F%uD877%uDC3A%uD839%uDC29
which then gets regex replaced with .replace(/u../g,''), but getting this string from minified javascript isn't easy for me.
simply running encodeURIComponent() or escape() doesn't get you quite there, though it gets you part of the way there.
So how do I get the string of my javascript converted into a string containing %uD then the character code for each?
I am also on dwitter.
The code compressor actually began with a dweet (https://www.dwitter.net/d/23092).
It was made so people could add more bytes into their demos by going right up to 194 chars instead of having the limit of 140.
Note this does not reduce the byte size.
Even though this reduces the amount of characters, the size stays the same
There is also an uncompressor at https://www.dwitter.net/d/14246
The simplified code for this is a simple unpack function:
function unpack(strange_blocky_code) {
const index = code.toLowerCase().search(/eval\(unescape\(escape`/g)
if (index >= 0) {
const start = strange_blocky_code.slice(0, index)
const end = strange_blocky_code.slice(index)
const result = eval(end.slice(4))
if (result) return start + result // returns readable (but trivial) code
}
}
The simplified compressing code is:
function compress(readable_code) {
const value = [...readable_code.trim()]
let code = ''
for (let character of value) {
const char = character.charCodeAt(0)
if (char > 255) character = escape(character).replace(/%u/g, "\\u")
code += character
}
const compressed =
String.fromCharCode(...[...code.length % 2 ? code + ";" : code]
.map((item, index) =>
item.charCodeAt() | (index % 2 ? 0xDF00 : 0xDB00)
)
)
return `eval(unescape(escape\`${compressed}\`.replace(/u../g,'')))`
}
If you're looking for editors, these are two that I like to use:
https://greyhope.uk/Dweet-Runner/index.html made by GreyHope
https://dweetabase.3d2k.com/ made by Frank Force
I hope this helps at all.
I have used the below code to split my string.
splitter.map((item1) => {
let splitter1 = item1.split("=")[0].trimLeft();
let splitter2 = item1.split("=")[1].trimRight();
});
where item1 contains string as
Labor_Agreement=0349BP
Default_Hours=5/8
Probation_Period=>=12 Months
The issue I am facing is to restrict the amount of splits. Because the above code will fail in case of third string , i.e. Probation_Period=>=12 Months
I tried giving parameter to restrict the amount of split in split method above, but that is giving syntax error.
An easy to understand solution would consist of first finding the first = character, and slicing you array twice to get the right portion :
const strings = [
'Labor_Agreement=0349BP',
'Default_Hours=5/8',
'Probation_Period=>=12 Months',
];
strings.map(item => {
const chSplit = item.indexOf('=');
const splitter1 = item.slice(0, chSplit).trim();
const splitter2 = item.slice(chSplit + 1).trim();
console.log(splitter1, splitter2);
});
If I do:
var number = 3500;
alert(number.toLocaleString("hi-IN"));
I will get ३,५०० in Hindi.
But how can I convert it back to 3500.
I want something like:
var str='३,५००';
alert(str.toLocaleNumber("en-US"));
So, that it can give 3500.
Is it possible by javascript or jquery?
I think you are looking for something like:
https://github.com/jquery/globalize
Above link will take you to git project page. This is a js library contributed by Microsoft.
You should give it one try and try to use formt method of that plugin. If you want to study this plugin, here is the link for the same:
http://weblogs.asp.net/scottgu/jquery-globalization-plugin-from-microsoft
I hope this is what you are looking for and will resolve your problem soon. If it doesn't work, let me know.
Recently I've been struggling with the same problem of converting stringified number formatted in any locale back to the number.
I've got inspired by the solution implemented in NG Prime InputNumber component. They use Intl.NumberFormat.prototype.format() (which I recommend) to format the value to locale string, and then create set of RegExp expressions based on simple samples so they can cut off particular expressions from formatted string.
This solution can be simplified with using Intl.Numberformat.prototype.formatToParts(). This method returns information about grouping/decimal/currency and all the other separators used to format your value in particular locale, so you can easily clear them out of previously formatted string. It seems to be the easiest solution, that will cover all cases, but you must know in what locale the value has been previously formatted.
Why Ng Prime didn't go this way? I think its because Intl.Numberformat.prototype.formatToParts() does not support IE11, or perhaps there is something else I didn't notice.
A complete code example using this solution can be found here.
Unfortunately you will have to tackle the localisation manually. Inspired by this answer , I created a function that will manually replace the Hindi numbers:
function parseHindi(str) {
return Number(str.replace(/[०१२३४५६७८९]/g, function (d) {
return d.charCodeAt(0) - 2406;
}).replace(/[०१२३४५६७८९]/g, function (d) {
return d.charCodeAt(0) - 2415;
}));
}
alert(parseHindi("३५००"));
Fiddle here: http://jsfiddle.net/yyxgxav4/
You can try this out
function ConvertDigits(input, source, target) {
var systems = {
arabic: 48, english: 48, tamil: 3046, kannada: 3302, telugu: 3174, hindi: 2406,
malayalam: 3430, oriya: 2918, gurmukhi: 2662, nagari: 2534, gujarati: 2790,
},
output = [], offset = 0, zero = 0, nine = 0, char = 0;
source = source.toLowerCase();
target = target.toLowerCase();
if (!(source in systems && target in systems) || input == null || typeof input == "undefined" || typeof input == "object") {
return input;
}
input = input.toString();
offset = systems[target] - systems[source];
zero = systems[source];
nine = systems[source] + 9;
for (var i = 0 ; i < input.length; i++) {
var char = input.charCodeAt(i);
if (char >= zero && char <= nine) {
output.push(String.fromCharCode(char + offset));
} else {
output.push(input[i]);
}
}
return output.join("");
}
var res = ConvertDigits('१२३४५६७८९', 'hindi', 'english');
I got it from here
If you need a jquery thing then please try this link
Use the Globalize library.
Install it
npm install globalize cldr-data --save
then
var cldr = require("cldr-data");
var Globalize = require("globalize");
Globalize.load(cldr("supplemental/likelySubtags"));
Globalize.load(cldr("supplemental/numberingSystems"));
Globalize.load(cldr("supplemental/currencyData"));
//replace 'hi' with appropriate language tag
Globalize.load(cldr("main/hi/numbers"));
Globalize.load(cldr("main/hi/currencies"));
//You may replace the above locale-specific loads with the following line,
// which will load every type of CLDR language data for every available locale
// and may consume several hundred megs of memory!
//Use with caution.
//Globalize.load(cldr.all());
//Set the locale
//We use the extention u-nu-native to indicate that Devanagari and
// not Latin numerals should be used.
// '-u' means extension
// '-nu' means number
// '-native' means use native script
//Without -u-nu-native this example will not work
//See
// https://en.wikipedia.org/wiki/IETF_language_tag#Extension_U_.28Unicode_Locale.29
// for more details on the U language code extension
var hindiGlobalizer = Globalize('hi-IN-u-nu-native');
var parseHindiNumber = hindiGlobalizer.numberParser();
var formatHindiNumber = hindiGlobalizer.numberFormatter();
var formatRupeeCurrency = hindiGlobalizer.currencyFormatter("INR");
console.log(parseHindiNumber('३,५००')); //3500
console.log(formatHindiNumber(3500)); //३,५००
console.log(formatRupeeCurrency(3500)); //₹३,५००.००
https://github.com/codebling/globalize-example
A common scenario for this problem is to display a float number to the user and then want it back as a numerical value.
In that case, javascript has the number in the first place and looses it when formatting it for display. A simple workaround for the parsing is to store the real float value along with the formatted value:
var number = 3500;
div.innerHTML = number.toLocaleString("hi-IN");
div.dataset.value = number;
Then get it back by parsing the data attribute:
var number = parseFloat(div.dataset.value);
This is a Columbus's egg style answer. It works provided the problem is an egg.
var number = 3500;
var toLocaleString = number.toLocaleString("hi-IN")
var formatted = toLocaleString.replace(',','')
var converted = parseInt(formatted)