I'm trying to get an input box to display numbers with space separator. Like this:
20 000 and 20 000 000 instead of 20000 and 20 000 000
The thing is that I want this to happen as you type. So when you type a number into an input element I want this spacing to be added on the fly.
Does anyone have a good solution for this?
I'm using this function to do this on static outputs, but it doesn't work well when getting the value from a textbox, running it through the function and then putting it back, for some reason.
function delimitNumber(number) {
var delimiter = " ";
number = new String(number);
var parts = number.split('.', 2);
var decimal = parts[1];
var i = parseInt(parts[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 (typeof decimal === 'undefined' || decimal.length < 1)
number = n;
else
number = n + '.' + decimal;
number = minus + number; // Assemble the number with negative sign (empty if positive)
return number;
}
<input type="text" id="number" />
JS:
$('#number').on("keyup", function() {
this.value = this.value.replace(/ /g,"");
this.value = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
});
http://jsfiddle.net/LLcsxr6c/
I used the keyup event because keypress or keydown will be triggered just before the input box is actually updated.
With jQuery 2 you can use $('#number').on("input", function()
Create a function that will do the string manipulation for you. Next, set up a listener on your input box to listen for a key down. That key down event should trigger your function, passing the value of your input box, and in turn setting the value to the newly spaced out string.
Related
I used below code to thousand and decimal separate in key up event. But after entering 15 digits value gets 0. what will be the reason ??
<script>
var myinput = document.getElementById('myinput');
myinput.addEventListener('keyup', function() {
var val = this.value;
val = val.replace(/[^0-9\.]/g,'');
if(val != "") {
valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
this.value = val;
});
</script>
<input id="myinput" type="text'>
Problem:
The problem here is that you reached the maximum possible value for Number on parseInt() when it tries to parse the input string value, check the Number.MAX_SAFE_INTEGER MDN Reference for further details.
So all the extra digits you enter, when the number exceeds the Number.MAX_SAFE_INTEGER, will be ignored and transformed to 0. Please check Working with large integers in JavaScript tutorial for more explanation and examples.
So, you can't treat a large number value as a Number in Javsacript because there's a Maximum possible value limit, you need to treat it as a string, so it can exceed this max value.
Solution:
The solution here is to treat this number as a string and use Regex and .replace() method to change its format.
Here's a solution that I wrote before and that I always use to format numbers, it will solve your problem:
var formatNumber = function(input, fractionSeparator, thousandsSeparator, fractionSize) {
fractionSeparator = fractionSeparator || '.';
thousandsSeparator = thousandsSeparator || ',';
fractionSize = fractionSize || 3;
var output = '',
parts = [];
input = input.toString();
parts = input.split(".");
output = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator).trim();
if (parts.length > 1) {
output += fractionSeparator;
output += parts[1].substring(0, fractionSize);
}
return output;
};
Demo:
This is a working Fiddle with your original code.
I have a form that will collect various data about properties. The user enters in values to select fields and onBlur, those values are formatted with comma's, dollar signs, and/or percentage signs.
I'm trying to create some real time calculations based on those inputs, but I'm having a hard time getting started on this. I have created a jfiddle page and have been playing around with ideas for the past few hours, but I just cannot seem to get the first calculation working.
I know I need to strip out any characters and have tried parseInt, parseFloat, replace, ect. Just nothing seems to work.
Thank you in advance.
function formatNumber(number, digits, decimalPlaces, withCommas)
{
number = number.toString();
var simpleNumber = '';
// Strips out the dollar sign and commas.
for (var i = 0; i < number.length; ++i)
{
if ("0123456789.".indexOf(number.charAt(i)) >= 0)
simpleNumber += number.charAt(i);
}
number = parseFloat(simpleNumber);
if (isNaN(number)) number = 0;
if (withCommas == null) withCommas = false;
if (digits == 0) digits = 1;
var integerPart = (decimalPlaces > 0 ? Math.floor(number) :
Math.round(number));
var string = "";
for (var i = 0; i < digits || integerPart > 0; ++i)
{
// Insert a comma every three digits.
if (withCommas && string.match(/^\d\d\d/))
string = "," + string;
string = (integerPart % 10) + string;
integerPart = Math.floor(integerPart / 10);
}
if (decimalPlaces > 0)
{
number -= Math.floor(number);
number *= Math.pow(10, decimalPlaces);
string += "." + formatNumber(number, decimalPlaces, 0);
}
return string;
}
function sumCalc() { // function to remove comma and then calculate
var glasf =
document.getElementById('gross_land_sf').value.replace(/,/g, "");
document.getElementById('gross_land_acre').value = formatNumber(glasf/43560);
}
https://jsfiddle.net/vva3x3wu/4/
Is this what you want ? I did some fixes:
https://jsfiddle.net/vva3x3wu/11/
In the link you put in the comment you removed class .cal from the first input, so calculations will not star until you tab from the last input.
Two part question.
Part 1 is easy, but I'm wondering what you think is the most elegant solution:
What would be the best procedure to use to convert input into cleanly formatted and WITH "normal" comma placement. The input could range from:
$8000
8200
8,000.50
And I want it to output simply: 8,000
Part 2, may be easy I just don't know the right operation. I want to round numbers so that: it is rounded based on the number of digits. So that there are TWO unrounded digits at all time.
45,643 should be 46,000
453 should be 450
59,023,920 should be 59,000,000
The following code should answer both parts of the question:
var input = "$820322310"; // String input
input = input.replace(/[^0-9\.]/g, ""); // remove all unnecessary characters
input = input.replace(/\.[0-9]+/, ""); // remove all after decimal (convert to integer)
if(parseInt(input[2]) >= 5) { // rounding to two decimal places
input[1] = input.slice(0, 1) + (parseInt(input[1]) + 1) + input.slice(2, input.length);
}
var count = 0;
for(var i = input.length-1; i >= 0; i--) {
if(i > 2) {
input = input.slice(0, i-1) + "0" + input.slice(i, input.length);
}
if(++count == 3 && i != 0) {
count = 0;
input = input.slice(0, i) + "," + input.slice(i, input.length);
}
}
See this at JSFiddle.
I'm trying to make a text field so that if there's a number 153.254, that becomes 153.25. And if the field contains 154.2, an extra 0 is added to fill two spots after decimal; 154.20.
toFixed() works great but I don't want the number rounded. Also came across other solutions where if I'm typing in 1.40, then if I move the cursor back after 1, I can't type anything in unless I clear the field and start over.
Is there a simple jQuery way to limit two characters after a decimal, and then if there's only one character after the decimal, add a zero to fill the two character limit?
(The field may receive value from database that's why the second part is required)
Solution Update: For those interested, I put this together to achieve what I wanted (Thanks to answers below and also other questions here on stackoverflow)
$('.number').each(function(){
this.value = parseFloat(this.value).toFixed(3).slice(0, -1);
});
$('.number').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(3).slice(0, -1);
}
}
return this; //for chaining
});
you could do myNumber.toFixed(3).slice(0, -1)
try this:
var num = 153.2
function wacky_round(number, places) {
var h = number.toFixed(2);
var r = number.toFixed(4) * 100;
var r2 = Math.floor(r);
var r3 = r2 / 100;
var r4 = r3.toFixed(2);
var hDiff = number - h;
var r4Diff = number - r3;
var obj = {};
obj[hDiff] = h;
obj[r4Diff] = r4;
if (r4Diff < 0) {
return h;
}
if (hDiff < 0) {
return r4;
}
var ret = Math.min(hDiff, r4Diff);
return obj[ret];
}
alert(wacky_round(num, 2))
How about
function doStuff(num){
var n = Math.floor(num * 100) / 100,
s = n.toString();
// if it's one decimal place, add a trailing zero:
return s.split('.')[1].length === 1 ? (s + '0') : n;
}
console.log(doStuff(1.1), doStuff(1.111)); // 1.10, 1.11
http://jsfiddle.net/NYnS8/
I have one TextBox in my UserControl. Here I want enter only positive or negative decimal number with three decimal places.
For example like below:
128.324, -23.453, 10, 0.453, -2, 2.34, -5.34
The TextBox should not allow to enter other characters. How to do this using JavaScript? I am not good enough in JavaScript.
If you validate on change your should be alright. Make sure you also validate any data that is sent to the server, on the server, since any data can be sent no matter how you try to validate it with JS:
var input = document.getElementById('tehinput');
input.onchange = function(){
var val = this.value, sign = '';
if(val.lastIndexOf('-', 0) === 0){
sign = '-';
val = val.substring(1);
}
var parts = val.split('.').slice(0,2);
if(parts[0] && parseInt(parts[0], 10).toString() !== parts[0]){
parts[0] = parseInt(parts[0], 10);
if(!parts[0])
parts[0] = 0;
}
var result = parts[0];
if(parts.length > 1){
result += '.';
if(parts[1].length > 3 ||
parseInt(parts[1], 10).toString() !== parts[1]){
parts[1] = parseInt(parts[1].substring(0,3), 10);
if(!parts[1])
parts[1] = 0;
}
result += parts[1];
}
this.value = sign+result;
}
JSFiddle
A regular expression to check content would be something like:
var re = /^[+-]?[\d,]+(\.\d{3})?$/;
but that will not enforce a comma for thousands, only allow it somewhere in the integer part. Note that in some countries, a comma is used for the decimal point.