Currently I am using following jQuery code to filter only digits:
$('#input_field').keyup(function(e) {
if (/\D/g.test(this.value)) {
this.value = this.value.replace(/\D/g, '');
}
});
But I want to get floating point numbers(upto to 2 decimal places) like this:
10.2
1.23
1000.10
Try this regex:
/^\d+(\.\d{0,2})?$/
Your JS:
$('#input_field').keyup(function(e) {
var regex = /^\d+(\.\d{0,2})?$/g;
if (!regex.test(this.value)) {
this.value = '';
}
});
try
toFixed(2)
eg:
var number = 2.234239;
var numberfixed=number.toFixed(2);
I think you have to use typing interval, because keyup is to quick and the regex don't approve something like this 0.
var typingTimer;
var doneTypingInterval = 1000;
$('.myInputField').keyup(function(){
clearTimeout(typingTimer);
if ($('.myInputField').val) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
function doneTyping () {
var vale = $('.myInputField').val();
var regexTest = /^\d+(?:\.\d\d?)?$/;
var ok = regexTest.test(vale);
if(!ok){
$('.myInputField').val('');
}
}
http://jsfiddle.net/jWbsE/
You need to change the regular expression used to test the values against.
/^\D+(\.\D\D?)?$/
This will allow numbers with no decimal point, or with a decimal point and one or two digits after.
var dot = fVal.split(".");
var len0 = 0;
var len1 = 0;
if (dot.length == 2) {
len0 = dot[0].length;
len1 = dot[1].length;
} else if (dot.length > 2)
len1 = 3;
else
len1 = 0;
var fValFlt = parseFloat(fVal);
var fValN = isNaN(fVal);
if ((len1 > 2) || fValN == true || fValFlt < 0) {
//failure arguments
} else {
//success arguments
}
In above code fVal is the field value for which you might be checking for.
Related
I am creating a fancy number box. The below is a function that when people finishing loading there ll be a number box count up to the result:
function countUp(count){
var div_by = 100,
speed = Math.round(count/div_by),
$display = $('.count'),// i bind the function to the class count
run_count = 1,
int_speed = 24;
var int = setInterval(function() {
if(run_count < div_by){
$display.text(speed * run_count);
run_count++;
} else if(parseInt($display.text()) < count) {
var curr_count = parseInt($display.text()) + 1;
$display.text(curr_count);
} else {
clearInterval(int);
}
}, int_speed);
}
countUp(6435);
It's working fine by i'd like to add comma to split the thousand like 6,345
I tried to convert the result using toString() but it doesn't work
countUp(6435).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
you can use toLocaleString method
countUp(6435).toLocaleString();
Simply try this one:
var num = countUp(6435);
num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
How to set auto 2 decimal number using value from id input type="text" javascript ?
http://jsfiddle.net/A4wxX/90/
First , fill data eg: 2 into input , it's will update input to 2.00
But not work When i user this
var numb = document.getElementById("int").value;
How can i do ? thank.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script type="text/javascript">
function fn_do() {
var numb = document.getElementById("int").value;
//var numb = 123;
var zzz = numb.toFixed(2);
document.getElementById("int").value = zzz;
}
</script>
<input type="text" id="int" onchange="fn_do()">
You should use parseFloat, because DOM property value is a string, not number.
var zzz = parseFloat(numb).toFixed(2)
And don't use parseInt, because it'll give you an integer, for example parseInt("1.2") will be 1, then toFixed(2) gives you 1.00, while you actually want 1.20 I assume.
One more thing to care is, make sure input content is valid, for example parseFloat('qwer') will give you NaN. So the final code would look like:
var zzz = (parseFloat(numb) || 0).toFixed(2);
Instead of
var zzz = numb.toFixed(2)
Try
var zzz = parseFloat(numb).toFixed(2) //use parseInt() or parsFloat() as shown here.
Your complete will look like this :-
function fn_do() {
var numb = document.getElementById("int").value;
var zz = parseFloat(numb) || 0; //it will convert numb to float if conversion fails it will return 0.
var zzz = zz.toFixed(2);
document.getElementById("int").value = zzz;
}
Fiddle
var decimalForm = parseFloat(Math.round( intNum * 100) / 100).toFixed(2);
alert(decimalForm );
If I'm understanding this correctly, you want whatever number is put into the object with the id 'int' to be automatically converted to a decimal value with two placeholders. You could do something like this:
function convertToDecimal(value) {
var tempValue = Nath.Round(parseFloat(value) * 100);
var returnValue = tempValue * .01;
return returnValue;
}
That would ensure that you always get two decimal places
Exceptions: 1. if tempValue is a multiple of 10, only one decimal will come out
2. if tempValue is a multiple of 100, no decimals will be returned
Solution:
function convertDecimals(convertedValue) {
var tempValue = Nath.Round(parseFloat(value) * 100);
if ((tempValue % 10) == 0) {
if ((tempValue % 100) == 0) { var returnValue = convertedValue + .00; return returnValue; } else {
var returnValue = convertedValue + 0;
return returnValue;
}
}
return '';
}
So maybe the whole cde would look like this
function fn_do() {
var numb = document.getElementById("int").value;
//var numb = 123;
var zzz = convertToDecimal(numb);
zzz = zzz + convertDecimal(zzz);
document.getElementById("int").value = zzz;
}
function convertToDecimal(value) {
var tempValue = Nath.Round(parseFloat(value) * 100);
var returnValue = tempValue * .01;
return returnValue;
}
function convertDecimals(convertedValue) {
var tempValue = Nath.Round(parseFloat(value) * 100);
if ((tempValue % 10) == 0) {
if ((tempValue % 100) == 0) { var returnValue = convertedValue + .00; return returnValue; } else {
var returnValue = convertedValue + 0;
return returnValue;
}
}
return '';
}
Javascript:
var validate(s) = s.match ^( 100(?:\.0{1,2})? | 0*?\.\d{1,2} | \d{1,2}(?:\.\d {1,2})? )% $ != null;
var str = value.match(/\/\/%//g);
if(converted==NaN){
alert('Input was not a number');
}
else if(converted != null) {
var fracToDecimal = eval (value);
alert(fracToDecimal);
}
else if(converted = str) {
var percToDecimal = value/100;
alert(percToDecimal);
} }
So you have a string like: 50%? How about:
var percent = "50%";
var result = parseFloat(percent) / 100.0;
If you use parseFloat, it will read the string up until the first non-number character (the %)
var x = '20.1%';
var y = parseFloat(x); // 20.1
Then you can check if it's NaN, and convert it.
if(!isNaN(y)){
y /= 100; // .201
}
Note: You need to use isNaN because NaN === NaN is false (JavaScript is weird).
UPDATE: I see you also have fracToDecimal in there. You don't need eval for that. Just do a simple split.
var frac = '1/2';
var nums = frac.split('/');
var dec = nums[0]/nums[1];
Assuming the "%" is on the right hand of the string, just use parseFloat(s)/100
http://jsfiddle.net/TrCYX/1/
I'm very late, but keeping it as itself if it is a decimal goes like this
let val = "100%"
String(val).includes("%") ? parseFloat(val)/100 : parseFloat(val) //1
val = 1 //or val = "1"
String(val).includes("%") ? parseFloat(val)/100 : parseFloat(val) //1
function convertToDecimal(percent) {
let newarr =[]
for(i=0; i<percent.length; i++) {
const parsed = parseFloat(percent[i]);
if (!Number.isNaN(parsed[i])) {
let newval = parseFloat(percent[i]) / 100;
//return newval;
newarr.push(newval)
} else {
return 0;
}
} return newarr;
}
console.log(convertToDecimal(["33%", "98.1%", "56.44%", "100%"]))
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;
}
How can when that typed numbers in input:text, separated them three to three and between them puting this:","?
normal number formatting
Example: typed this number in input: 45656839
result (live - online) in same input: 45,656,839
i not want use of plugin.
With respect
Demo
This should do it for you.
<input type="text" class="numeric" />
$("input:text.numeric").keyup(function(){
$val = $(this).val();
$(this).val($val.match(/[0-9]{1,3}/g).join(","))
});
EDIT
For normal number formatting, the code is a little different. There's probably a some good regex out there for this but my first thought was to reverse the string and apply the same technique. Then you reverse the string again and you have it
$("input:text.numeric").keyup(function(){
$val = $(this).val().match(/[0-9]/g).reverse().join("").match(/[0-9]{1,3}/g).join(",").match(/./g).reverse().join("");
$(this).val($val)
});
EDIT 2
Demo
And for future reference if anyone wants to implement this with decimal places (yeah I got carried away :P) ...
$("input:text.numeric").keyup(function(e){
if(e.which > 40 || e.which == 8) {
var num = $(this).val().match(/[0-9,]*/g)[0];
var decimalNum = $(this).val().match(/[.][0-9]*/) || "";
if(num) {
var wholeNum = num.match(/[0-9]/g).reverse().join("").match(/[0-9]{1,3}/g).join(",").match(/./g).reverse().join("");
var resultNum = wholeNum + decimalNum;
$(this).val(resultNum);
}
else
{
$(this).val(num);
}
}
});
I think that masked input plugin could be a good solution. You can read more here: http://digitalbush.com/projects/masked-input-plugin/
function thousandSeparator(n,sep) {
var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
sValue=n+'';
if (sep === undefined) {sep=',';}
while(sRegExp.test(sValue)) {
sValue = sValue.replace(sRegExp, '$1'+sep+'$2');
}
return sValue;
}
From: http://webdesign.onyou.ch/2010/08/04/javascript-inserting-thousand-separators/
Just do something like this (untested, should work):
$(':text').blur(function(){
var $this = $(this), val = $this.val(), newVal = ''
for (var i = 0; i < val.length; i++) {
newVal += val.charAt(i)
if (!((i + 1) % 3))
newVal += ','
}
$this.val(newVal.slice(0,-1))
})
Edit: See Joseph's answer above. His is shorter.