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..
Related
Using JavaScript, I want to show up to two decimal places, a comma, and a comma after two integers, but I tried to show up to nine digits using integers, but I'm not good at showing two integers and two decimal places.
(like 1.50% or 50.00% or 99.99%...etc)
If enter more digits than that, I want to prevent it from entering.
// Thousand commas (including decimal point)
function numberWithCommas(num) {
var parts = num.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
//Number + - check (remove all non-numeric + - values) Up to 9 numbers
function chkNumber(obj) {
var tmpValue = $(obj).val().replace(/[^0-9,^\-]/g, '');
tmpValue = tmpValue.replace(/[,]/g, '');
tmpValue = tmpValue.substring(0, 9);
// Forced value change after processing thousands commas
obj.value = numberWithCommas(tmpValue);
}
// Remove anything other than numeric values
function chkrealNumber(obj) {
var tmpValue = $(obj).val().replace(/[^0-9,]/g, '');
obj.value = tmpValue.replace(/[,]/g, '');
}
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;
}
function dec2bin (decimal) {
var x = document.getElementById("deci").value;
if ((/[^0-9]/g.test(x)) || x == "") {
alert ("You must enter an integer decimal number!");
document.getElementById("deci").value = "";
document.getElementById("deci").focus();
return false;
}
x = parseInt(x);
var bin = x.toString(2);
var figs = "The binary representation of " + x + " is " + bin + "<br>";
document.getElementById("result").innerHTML = figs;
This is the sample code my teacher gave us. It is a decimal to binary converter. I'm not entirely sure what some of these symbols mean. For example, the if statement. What exactly does
(/[^0-9]/g.test(x)) || x == "")
do? Also what exactly does
x = parseInt(x);
var bin = x.toString(2);
accomplish, I kind of understand but would like futher explanation .
/[^0-9]/g is a regular expression that matches anything that isn't a decimal digit. So /[^0-9]/g.test(x) will be true if x contains any non-digits. x == "" is true if x is an empty string. Combining them, (/[^0-9]/g.test(x)) || x == "") is true if x is empty or contains non-digits. In other words, it's true if the input isn't a sequence of decimal digits. You can learn more about regular expressions at http://www.regular-expressions.info/
x = parseInt(x); calls the Javascript parseInt() function, which converts a string representing an integer into an integer. BTW, you should always provide the second argument to specify the radix, as it may differ between implementations; it should usually be x = parseInt(x, 10); to indicate that you're parsing decimal.
var bin = x.toString(2); calls the Javascript Number.prototype.toString method. This converts a number to a string in the specified output radix. Radix 2 is binary.
Just wondering if anyone can work out why I keep getting for eg. 3+3=33 and not 6.
The rest of the coding works fine for the divide and times its the addition that keeps stuffing up and wont come up with the correct answer.. please help if you can.
here is my code:
<html>
<head>
<title>Practical Task 8 </title>
</head>
<body>
<button onclick="myFunction()">Press & Enter First Digit & Second Digit</button>
<script type="TEXT/JavaScript">
function myFunction()
{
var x=prompt("Please enter first number","0");
var y=prompt("Please enter second number","0");
var sum = x;
var sum2 = y;
var n = (x * y);
var n2 = (x / y);
var n3 = (x + y);
document.write(sum + " + " + sum2 + " = " + n3);
document.write("<BR>" + sum + " * " + sum2 + " = " + n);
document.write("<BR>" + sum + " / " + sum2 + " = " + n2);
}
</script>
</body>
</html>
You're performing string concatenation, not integer addition.
Use parseInt first:
x = parseInt( x, 10 );
y = parseInt( y, 10 );
MDN recommends always specifying the radix (the 10 part) to avoid problems, such as if a user prepends a number with 0 (where it'll be parsed as octal), or if different browsers have a different default radix (wtf, I know!).
You have to do this because the output of prompt is always a string, even if it's a number (e.g. "10" or "0123"), you need to tell JavaScript to interpret the data as a number (use parseInt if it's an integer (a whole number), or use parseFloat if you'll accept numbers with decimal places). Confusingly the + operator works for both string and number types, where it performs either concatenation (i.e. joining strings together like glue) or addition depending on the type of its operands.
Because your code is adding strings.
User input is always string.
You need to parseInt(x, 10) and parseInt(y, 10) to parse the string value into int base 10.
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, ",");
}