Why am I getting NaN with this attempt at rounding (javascript)? - javascript

I've got this code to add a value above a bar in a Chart.JS bar chart:
//ctx.fillText(addCommas(dataset.data[i]), model.x, y_pos);
ctx.fillText(addCommasRound(dataset.data[i]), model.x, y_pos);
The old code (using addCommas()) worked, changing values such as "1838204.79" to "1,838,204.79"
I want to ignore the cents/decimals, though, so I tried an alternative addCommasRound() method like this:
function addCommasRound(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 Math.round(x1 + x2);
}
The only difference between addCommas() and addCommasRound() is the insertion of MathRound() into the return statement. Why does this cause the value to be "NaN" instead of "1,838,205"?
I also tried changing the last line to:
return Math.round(x1);
...just to see if it would not fail, but with the same ("NaN") result.

Commas are not allowed in numeric literals. Math.round attempts to convert the parameters to numbers.
Executing +'1,000' produces NaN, whereas +'1000' produces 1000.
If you want to add commas to the numbers you're returning, round first, and then add commas.

Because x1 and x2 are not numbers (which is what NaN stands for), they are strings.
You need to round the number first, then perform the string operations.
function addCommasRound(nStr) {
nStr = String(Math.round(Number(nStr)));
See also JavaScript string and number conversion.

Based on OrangeDog's answer, I came up with this working derivation:
function addCommasRound(nStr) {
nStr = String(Math.round(Number(nStr)));
x = nStr.split('.');
x1 = x[0];
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1;
}

Related

Javascript not displaying strings with " ' " in them

I am writing a Javascript function where strings with apostrophe ( ' ) are not being displayed. Is there a way I can go around this? The below function assumes x is a string.
function addItem(x, y) //adds item on screen and adds Total
{
var newRow = "<tr><td>"+x+"</td><td>€"+y.toFixed(2)+"</td><td><input type=\"button\" onclick=\"subtract("+y+")\" value = \"X\"></td></tr>"
$('#order').append(newRow);
document.getElementById("currentorder").value += newRow;
//Adds Total Value
var total = document.getElementById('price').innerHTML;
total = parseFloat(total);
var z = +y + +total;
document.getElementById('price').innerHTML=z.toFixed(2);
event.preventDefault();
}
Confusing Addition Operators
The following line looks quite a bit off :
var z = +y + +total;
If you just want to add y and total, just simplify it as :
var z = y + total;
Consider Possible Parsing Errors
Another idea would be to consider stripping out any non float related characters (i.e. non decimals and digits) within your string prior to calling your parseFloat() function :
var total = parseFloat(document.getElementById('price').innerHTML.replace(/[^\d\.]/g,''));

The adding up button doesn't work in javascript

I made a simple calculator in javascript but the + button doesn't work and it just show the numbers near together
Here is my code:
<script>
function calc(operator) {
var x = document.getElementById("inp1").value;
var y = document.getElementById("inp2").value;
var z = 0;
switch (operator) {
case "+":
z = x + y;
break;
case "-":
z = x - y;
break;
case "*":
z = x * y;
break;
case "/":
z = x / y;
break;
}
document.getElementById("result").innerHTML=z;
}
</script>
You may use like this:
z= +x + +y; // + is prefixed to convert input into number
The x and y variables contain strings. Parse them to numbers:
var x = parseFloat(document.getElementById("inp1").value);
var y = parseFloat(document.getElementById("inp2").value);
It happens to work for the other operators, because there are no subtraction, multiplication or division for strings, it figures out that it has to convert the strings to numbers.
var x=document.getElementById("inp1").value;
var y=document.getElementById("inp2").value;
return you values in those text boxes as strings.
When you use + operator on strings, it will concatenate the values. If you use the same operator on numbers, it will add the values.
You will need to parse the text box values into integer using the parseInt function using one of the following ways.
var x=parseInt(document.getElementById("inp1").value);
var y=parseInt(document.getElementById("inp2").value);
and then do z=x+y; I would recommend this because all the operations, not just addition, will be perfomed on the integers.
or simply change z=z+y; to look like z = parseInt(x) + parseInt(y);
A quick way to convert a string to a number is to use the unary + operator.
z = +x + +y
or
z = parseInt(x) + parseInt(y);
var x = parseInt(document.getElementById("inp1").value);
this converts your "string" number to integer, also you can use parseFloat() if you have float numbers
You may use like this:
var x = document.getElementById("inp1").value*1;
var y = document.getElementById("inp2").value*1;
x in this moment is number!!
More clean for me!!!

Automatically truncate 8 digits with two decimals

I have textbox of Maxlength(11) allowing 8 digits, 1 decimal point and 2 precision. I have the following cases:
If the user keys in 11 digits, it must consider the first 8 digits, add a decimal point, then use the next two for precision.
If the user enters a whole digit alone, it must autoappend .00.
When leaving the textbox, it adds commas within the digits. Eg, 12,345,678.90
I am using the below function to add commas
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;
}
// Using toFixed(2) to make .00
I am not able to automatically,adjust the available values. Do you have any suggestions to make all this in one function? Can anyone help me to resolve this?
Ok, why don't you use javascript substring function, and simple if else condition..
Created the Plnkr Link for your reference, if this is what you want..

How to add commas format in number after page load using jquery

I have one page which is having bank funds summary details and i am getting all these value from API. These values are not formatted for example like 50000.3645656.
So here is my page structure given below
<span class="format">50000.3645656</span>
<span class="format">50000.3645656</span>
<span class="format">50000.3645656</span>
<span class="format">50000.3645656</span>
<span class="format">50000.3645656</span>
So what i want exactly is , I want to format all these value with comma formated with two decimal point like 50,000.36.
How can i do this after page load using jquery and css class format in jquery method.
As far as I know, you can't do this using pure CSS.
However, you could use a JavaScript function to add commas for you.
I have used this one in the past:
function addCommas(nStr)
{
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Reference
And then do your jquery:
$(function(){
$(".format").each(function(c, obj){
$(obj).text(addCommas(parseFloat($(obj).text()).toFixed(2)));
});
});
JSfiddle Demonstration:
As an alternative why not using a tiny library that does the job well:
http://josscrowcroft.github.io/accounting.js/
Use:
var input = '55021.1231';
var parts = input.split('.');
var part1 = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
var part2 = parseFloat('0.'+parts[1]).toFixed(2);
part2=part2.split('.');
alert(part1 + '.' + part2[1]);
Demo

Adding comma as thousands separator (javascript) - output being deleted instead

I am attempting to dynamically adjust a numerical value entered to include thousand separators
Here is my code:
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;
}
<input type="number" onkeyup="this.value=addCommas(this.value);" />
However when I enter numbers after the 4 one, the field is cleared.
Any ideas where I am going wrong? If there is a jQuery solution I'm already using that on my site.
Try this regex:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
To add the thousands separator you could string split, reverse, and replace calls like this:
function addThousandsSeparator(input) {
var output = input
if (parseFloat(input)) {
input = new String(input); // so you can perform string operations
var parts = input.split("."); // remove the decimal part
parts[0] = parts[0].split("").reverse().join("").replace(/(\d{3})(?!$)/g, "$1,").split("").reverse().join("");
output = parts.join(".");
}
return output;
}
addThousandsSeparator("1234567890"); // returns 1,234,567,890
addThousandsSeparator("12345678.90"); // returns 12,345,678.90
Try
<input type="text" onkeyup="this.value=addCommas(this.value);" />
instead. Since the function is working with text not numbers.
as Dillon mentioned, it needs to be a string (or you could use typeof(n) and stringify if not)
function addCommas(n){
var s=n.split('.')[1];
(s) ? s="."+s : s="";
n=n.split('.')[0]
while(n.length>3){
s=","+n.substr(n.length-3,3)+s;
n=n.substr(0,n.length-3)
}
return n+s
}
In each case before formatting try to remove existing commas first, like there: Removing commas in 'live' input fields in jquery
Example:
function addThousandsSeparator(x) {
//remove commas
retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;
//apply formatting
return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Categories