JavaScript - Commas as thousands separators [duplicate] - javascript

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Format numbers in JavaScript similar to C#
(17 answers)
Closed 8 years ago.
Can you help me changing that variable to make commas as thousand separators?
var number1 = 123456789;
$(function(){
document.getElementById("test").innerHTML("Var number1 is: " + number1); //i want that to display with commas
}
I don't understand answers on other questions like that. Thanks

You may look at some answers here:
http://www.queness.com/post/9806/5-missing-javascript-number-format-functions
but here's the code from the same page:
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;
}
/**
* Usage: CommaFormatted(12345678);
* result: 12,345,678
**/

Related

Given a natural number N. What is the sum of the numbers N? [duplicate]

This question already has answers here:
Sum all the digits of a number Javascript
(8 answers)
Closed 1 year ago.
I tried to solve but didn't work :
const SumOf = (N) => {
var res = N.toString().split("");
var total = 0;
for (i = 0; i < N; i++) {
total += res[i]
}
}
You can simply write:
const sumN = (number) => {
const nArray = number.split("").map(n=> +n)
return nArray.reduce((acc, cur)=> acc+=cur, 0)
}
console.log(sumN("123"))

How to add a variable in javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
var count=0 ;
for(var x=0; x<data_len; x++)
{
count = count + num_arr[x];
}
// alert(count);
If count = 352 I want to add 3+5+2 which is 10 and then 1+0 which is 1.
function sumParts(x) {
var sumX = 0;
var strX = x.toString();
var arrX = strX.split("");
for (a = 0; a < arrX.length; a++) {
sumX += parseInt(arrX[a], 10);
};
return sumX;
}
y = sumParts(count);
z = sumParts(y);
// y = 10; (3 + 5 + 2)
// z = 1; (1 + 0)
And, I believe (untested), if the return was changed to return sumParts(sumX), it would continue until it was a single digit integer.
You have an array of strings, not numbers. You can convert them to numbers with:
count = count + +num_arr[x];
The second + is the unary plus operator, and will cast num_arr[x] to a number.
If your numbers are all integers, you can use:
count = count + parseInt(num_arr[x], 10);
or (if you have floats):
count = count + parseFloat(num_arr[x]);
Convert count into a string :
var count = 352;
count += ''; // makes a string : "352"
while (count.length > 1) {
count = Function('return ' + count.split('').join('+') + ';')() + '';
}
This part :
Function('return ' + count.split('').join('+') + ';')
Gives successively :
function () { return 3+5+2; }
function () { return 1+0; }

Javascript rounding issue when summing values [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript's Math broken?
The user enters values in the first two text boxes and, as they type, Javascript (sorry, no jQuery, I'm not up to it yet) is used to calculate the precise sum and the sum rounded to 2 digits.
Why am I getting rounding error and what can I do to correct it?
Many thanks.
Hmmm....ParseFloat? Wrong data type?
What I would like to see if the precise answer as if it were added on a calculator. Is there a parseDecimal or other data type that I can use?
![enter image description here][1]
function SumValues() {
//debugger;
var txtSubsContrRbtAmt = document.getElementById("<%=txtSubsContrRbtAmt.ClientID%>");
var txtDeMinAmt = document.getElementById("<%=txtDeMinAmt.ClientID%>");
var txtTotRbtAmt = document.getElementById("<%=txtTotRbtAmt.ClientID%>");
var txtRndRbtAmt = document.getElementById("<%=txtRndRbtAmt.ClientID%>");
var total = Add(txtSubsContrRbtAmt.value, txtDeMinAmt.value);
txtTotRbtAmt.value = total;
txtRndRbtAmt.value = RoundToTwoDecimalPlaces(total);
}
function Add() {
var sum = 0;
for (var i = 0, j = arguments.length; i < j; i++) {
var currentValue;
if (isNumber(arguments[i])) {
currentValue = parseFloat(arguments[i]);
}
else {
currentValue = 0;
}
sum += currentValue;
}
return sum;
}
function RoundToTwoDecimalPlaces(input) {
return Math.round(input * 100) / 100
}
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
[1]: http://i.stack.imgur.com/5Otrm.png
Update. I am evaluating something like this:
function AddWithPrecision(a, b, precision) {
var x = Math.pow(10, precision || 2);
return (Math.round(a * x) + Math.round(b * x)) / x;
}
There is a golden rule for anyone writing software in the financial sector (or any software dealing with money): never use floats. Therefore most software dealing with money use only integers and represent decimal numbers as a data structure.
Here's one way of doing it:
(Note: this function adds two strings that looks like numbers)
(Additional note: No error checking is done to aid clarity. Also does not handle negative numbers)
function addNumberStrings (a,b) {
a = a.split('.');
b = b.split('.');
var a_decimal = a[1] || '0';
var b_decimal = b[1] || '0';
diff = a_decimal.length - b_decimal.length;
while (diff > 0) {
b_decimal += '0';
diff --;
}
while (diff < 0) {
a_decimal += '0';
diff ++;
}
var decimal_position = a_decimal.length;
a = a[0] + a_decimal;
b = b[0] + b_decimal;
var result = (parseInt(a,10)+parseInt(b,10)) + '';
if (result.length < decimal_position) {
for (var x=result.length;x<decimal_position;x++) {
result = '0'+result;
}
result = '0.'+result
}
else {
p = result.length-decimal_position;
result = result.substring(0,p)+'.'+result.substring(p);
}
return result;
}
*note: code is simplified, additional features left out as homework.
To fix your addition the way you want, I'd suggest counting the decimal places in each number somehow This method, for instance Then passing the max value to toFixed, and trimming any leftover zeroes.
function AddTwo(n1, n2) {
var n3 = parseFloat(n1) + parseFloat(n2);
var count1 = Decimals(n1, '.');
var count2 = Decimals(n2, '.');
var decimals = Math.max(count1, count2);
var result = n3.toFixed(decimals)
var resultDecimals = Decimals(result, '.');
if (resultDecimals > 0) {
return result.replace(/\.?0*$/,'');
}
else {
return result;
}
}
// Included for reference - I didn't write this
function Decimals(x, dec_sep)
{
var tmp=new String();
tmp=x;
if (tmp.indexOf(dec_sep)>-1)
return tmp.length-tmp.indexOf(dec_sep)-1;
else
return 0;
}
Here's a JSFiddle of that

String toFixed with javascript?

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

How can I convert a Guid to a Byte array in Javascript?

I have a service bus, and the only way to transform data is via JavaScript. I need to convert a Guid to a byte array so I can then convert it to Ascii85 and shrink it into a 20 character string for the receiving customer endpoint.
Any thoughts would be appreciated.
Try this (needs LOTS of tests):
var guid = "{12345678-90ab-cdef-fedc-ba0987654321}";
window.alert(guid + " = " + toAscii85(guid))
function toAscii85(guid)
{
var ascii85 = ""
var chars = guid.replace(/\{?(?:(\w+)-?)\}?/g, "$1");
var patterns = ["$4$3$2$1", "$2$1$4$3", "$1$2$3$4", "$1$2$3$4"];
for(var i=0; i < 32; i+=8)
{
var block = chars.substr(i, 8)
.replace(/(..)(..)(..)(..)/, patterns[i / 8]) //poorman shift
var decValue = parseInt(block, 16);
var segment = ""
if(decValue == 0)
{
segment = "z"
}
else
{
for(var n = 4; n >= 0; n--)
{
segment = String.fromCharCode((decValue % 85) + 33) + segment;
decValue /= 85;
}
}
ascii85 += segment
}
return "<~" + ascii85 + "~>";
}
Check the unparse() method in node-uuid package and its example here:
https://www.npmjs.com/package/node-uuid#uuid-unparse-buffer-offset

Categories