Internationally pretty print string objects that contain decimals - javascript

I am using MikeMcl's big.js for precise accounting which outputs a string when calling toFixed().
I'd like to pretty print decimal results in an internationally aware way much like how the Date Object can automatically print dates and times in a local format.
Is there a way to format string objects that contain decimals internationally?

var myNumber = 123456.78;
console.log(myNumber.toLocaleString());

This should do the job.
function localize(fixed) {
/*Determine decimal symbol and digit grouping symbol.*/
var decimalSymbol = '.';
var digitGroupingSymbol = ',';
var dummy = 1234.5;
testResult = dummy.toLocaleString();
/*Browsers using digit grouping symbol.*/
if (testResult.length === 7) {
decimalSymbol = testResult[5];
digitGroupingSymbol = testResult[1];
}
/*Browsers not using digit grouping symbol.*/
if (testResult.length === 6) {
decimalSymbol = testResult[4];
digitGroupingSymbol = (decimalSymbol === '.'? ',': '.');
}
/*Format the number.*/
var result = '';
var dsIndex = fixed.indexOf('.');
if (dsIndex < 0) {
throw new Error('Expected decimal separator \'.\' in "' + fixed + '".');
}
for (var i = 0; i < dsIndex; ++i) {
if (fixed[i] < '0' || fixed[i] > '9') {
throw new Error('Expected digit, got "' + fixed[i] + '".');
}
if (i > 0 && i%3 === dsIndex%3) result += digitGroupingSymbol ;
result += fixed[i];
}
result += decimalSymbol + fixed.substr(dsIndex + 1);
return result;
}
/*Demonstration*/
var n1 = '123.4567890';
console.assert(localize(n1));
var n2 = '1234.567890';
console.log(localize(n2));
var n3 = '123456789012345678.1234567890';
console.log(localize(n3));
var n4 = '1234567890123456789.1234567890';
console.log(localize(n4));
var n5 = '12345678901234567890.1234567890';
console.log(localize(n5));
Output:
123.4567890
1.234.567890
123.456.789.012.345.678.1234567890
1.234.567.890.123.456.789.1234567890
12.345.678.901.234.567.890.1234567890

Related

Can't convert string to number

I have a large text from which I read data according to the scheme. Key words are placed in the "smallArtName" array. The scheme looks like this:
(key word) xxx (cordX|cordY)
I can't convert the string I received to a number. It seems to me that the reason is white space, visible in the terminal in the picture. I tried to use the replace method which works for sample text, but not for my value.
I'm a beginner and I could probably do it simpler, but the code I wrote works, and this is the most important thing for now.
for (i = 0; i < smallArtName.length; i++) {
var n = art.artPrintScreen.indexOf(smallArtName[i]);
if (n > 0) {
var tempString = art.artPrintScreen.substring(n, n + 100);
betweenChar = tempString.indexOf('|');
for (k = betweenChar - 10; k <= betweenChar + 10; k++) {
if (tempString[k] == '(') {
xStart = k;
}
if (tempString[k] == ')') {
yEnd = k;
}
}
cordX = tempString.slice(xStart + 1, betweenChar);
cordY = tempString.slice(betweenChar + 1, yEnd);
strTest = " t est".replace(/\s/g, '')
var cordY2 = cordY.replace(/\s/g, '')
console.log(typeof (cordY))
console.log(cordY2)
console.log(cordY2[0])
console.log(cordY2[1])
console.log(cordY2[2])
console.log(cordY2[3])
console.log(cordY2[4])
console.log(cordY2[5])
console.log(strTest)
var cordYtest = parseInt(cordY2, 10);
console.log(cordYtest)
}
}
You just need to change the regex so that you replace everything except digits and the negative sign - rather than just whitespace. i.e.
change
var cordY2 = cordY.replace(/\s/g, '')
to
var cordY2 = parseInt(cordY.replace(/[^0-9-]/g, ''), 10);
So that the variable cordY2 contains the number you require.

Evaluation for all purposes JavaScript

I want an eval() function which will calculate brackets as same as normal calculations but here is my code
var str = "2(3)+2(5)+7(2)+2"
var w = 0;
var output = str.split("").map(function(v, i) {
var x = ""
var m = v.indexOf("(")
if (m == 0) {
x += str[i - 1] * str[i + 1]
}
return x;
}).join("")
console.log(eval(output))
Which takes the string str as input but outputs 61014 and whenever I try evaluating the output string, it remains same.
Obligatory "eval() is evil"
In this case, you can probably parse the input. Something like...
var str = "2(3)+2(5)+7(2)+2";
var out = str.replace(/(\d+)\((\d+)\)/g,(_,a,b)=>+a*b);
console.log(out);
while( out.indexOf("+") > -1) {
out = out.replace(/(\d+)\+(\d+)/g,(_,a,b)=>+a+(+b));
}
console.log(out);
You can do it much simplier, just insert '*' in a right positions before brackets
var str = "2(3)+2(5)+7(2)+2"
var output = str.replace(/\d\(/g, v => v[0] + '*' + v[1])
console.log(eval(output))

Adding a comma at every third number character

In my code I have a variable myCash, which is printed into an h1 element using javaScript's innerHTML. I found a function online that puts a comma after every third character from the end of the number so that the number is easier to read. I've tried for a couple of hours now sending my variable myCash into the function and then print it on the screen. I CANNOT get it to work.
I've tried just alerting the new variable to the screen after page load or by pressing a button, but I get nothing and the alert doesn't even work. Here's the comma insert function:
function commaFormatted(amount) {
var delimiter = ","; // replace comma if desired
amount = new String(amount);
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;
return amount;
}
now when I want my variable to change I've tried it a few different ways including this:
var newMyCash = commaFormatted(myCash);
alert(newMyCash);
and this:
alert(commaFormatted(myCash);
Where of course myCash equal some large number;
This does absolutely nothing! What am I doing wrong here??
Also,
Try this as a drop in replacement and try alerting the response:
http://phpjs.org/functions/number_format:481
Do you see any errors in the console of your browser (usually f12)?
This is not my function, but I hope it helps you.
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Usage:
var newMyCash = addCommas( myCash ); alert( newMyCash );
Source: http://www.mredkj.com/javascript/nfbasic.html
You are most likely not passing in a number that contains a decimal, which the function expects.
Working Demo

how to get formatted integer value in javascript

This is my integer value
12232445
and i need to get like this.
12,232,445
Using prototype how to get this?
var number = 12232445,
value = number.toString(),
parts = new Array;
while (value.length) {
parts.unshift(value.substr(-3));
value = value.substr(0, value.length - 3);
}
number = parts.join(',');
alert(number); // 12,232,445
It might not be the cleanest solution, but it'll do:
function addCommas(n)
{
var str = String(n);
var result = '';
for(var i = 0; i < str.length; i++)
{
if((i - str.length) % 3 == 0)
result += ',';
result += str[i];
}
return result;
}
Here is the function I use, to format thousands separators and takes into account decimals if any:
function thousands(s) {
var rx = /(-?\d+)(\d{3})/,
intDec = (''+s)
.replace(new RegExp('\\' + $b.localisation.thousandSeparator,'g'), '')
.split('\\' + $b.user.localisation.decimalFormat),
intPart = intDec[0],
decPart = intDec[1] || '';
while (rx.test(intPart)) {
intPart = intPart.replace(rx,'$1'+$b.localisation.thousandSeparator+'$2');
}
return intPart + (decPart && $b.localisation.decimalFormat) + decPart;
}
thousands(1234.56) //--> 1,234.56
$b.localisation is a global variable used for the session.
$b.localisation.thousands can have the values , or . or a space.
And $b.localisation.decimalFormat can have the values , or . depending on the locale of the user

Adding commas, decimal to number output javascript

I'm using the following code to count up from a starting number. What I need is to insert commas in the appropriate places (thousands) and put a decimal point in front of the last two digits.
function createCounter(elementId,start,end,totalTime,callback)
{
var jTarget=jQuery("#"+elementId);
var interval=totalTime/(end-start);
var intervalId;
var current=start;
var f=function(){
jTarget.text(current);
if(current==end)
{
clearInterval(intervalId);
if(callback)
{
callback();
}
}
++current;
}
intervalId=setInterval(f,interval);
f();
}
jQuery(document).ready(function(){
createCounter("counter",12714086+'',9999999999,10000000000000,function(){
alert("finished")
})
})
Executed here: http://jsfiddle.net/blackessej/TT8BH/3/
var s = 121221;
Use the function insertDecimalPoints(s.toFixed(2));
and you get 1,212.21
function insertDecimalPoints(s) {
var l = s.length;
var res = ""+s[0];
console.log(res);
for (var i=1;i<l-1;i++)
{
if ((l-i)%3==0)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res = res.replace(',.','.');
return res;
}
Check out this page for explanations on slice(), split(), and substring(), as well as other String Object functions.
var num = 3874923.12 + ''; //converts to a string
numArray = num.split('.'); //numArray[0] = 3874923 | numArray[1] = 12;
commaNumber = '';
i = numArray[0].length;
do
{
//we don't want to start slicing from a negative number. The following line sets sliceStart to 0 if i < 0. Otherwise, sliceStart = i
sliceStart = (i-3 >= 0) ? i-3 : 0;
//we're slicing from the right side of numArray[0] because i = the length of the numArray[0] string.
var setOf3 = numArray[0].slice(sliceStart, i);
commaNumber = setOf3 + ',' + commaNumber; //prepend the new setOf3 in front, along with that comma you want
i -= 3; //decrement i by 3 so that the next iteration of the loop slices the next set of 3 numbers
}
while(i >= 0)
//result at this point: 3,874,923,
//remove the trailing comma
commaNumber = commaNumber.substring(0,commaNumber.length-1);
//add the decimal to the end
commaNumber += '.' + numArray[1];
//voila!
This function can be used for if not working locale somite
number =1000.234;
number=insertDecimalPoints(number.toFixed(3));
function insertDecimalPoints(s) {
console.log(s);
var temaparray = s.split(".");
s = temaparray[0];
var l = s.length;
var res = ""//+s[0];
console.log(res);
for (var i=0;i<l-1;i++)
{
if ((l-i)%3==0 && l>3)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res =res +"."+temaparray[1];
return res;
}
function convertDollar(number) {
var num =parseFloat(number);
var n = num.toFixed(2);
var q =Math.floor(num);
var z=parseFloat((num).toFixed(2)).toLocaleString();
var p=(parseFloat(n)-parseFloat(q)).toFixed(2).toString().replace("0.", ".");
return z+p;
}

Categories