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, '');
}
Related
Can someone show me how to write a function that adds 0's after the decimal if less than four digits appear after the decimal until 4 decimal spots long and trim digits from far right of decimal in excess of 4. These are strings. Don't want any rounding. For display only, not calculations. So for example:
719.843797 should remove last two digits to be 719.8437
21.947 should add one 0 to be 21.9470
1.3456 no change
Using toFixed or any sort of multiplication may result in rounding problems. Treating number as a string allows to avoid them. The function below passes all your given usecases. But this is kinda hacky. Though I'm not sure if there is a better way to fit your requirements.
function truncate4(x) {
var parts = x.toString().split('.'); // this is not i18n proof :(
var integral = parts[0];
var decimal = parts[1] || ''; // might be integer
return integral + '.' + (decimal + '0000').substr(0, 4)
}
console.log(truncate4(719.843797));
console.log(truncate4(21.947));
console.log(truncate4(1.3456));
This function should match
function arrondir(num){
var str = num.toString();
var index = str.indexOf(".");
var decimal = str.substr(index+1);
var integer = str.substr(0, index);
if (decimal.length < 4)
for (var i = 0; i < 5 - decimal.length; i++)
decimal = decimal.concat("0");
else decimal = decimal.substr(0,4);
return integer.concat(".").concat(decimal);
}
console.log(arrondir(719.84)); // 719.8400
console.log(arrondir(719.84657963657)); // 719.8465
e.g.,
var myNum = 1.208452
I need to get the last digit of myNum after decimal so it is (2)
You could try something like:
var temp = myNum.toString();
var lastNum = parseInt(temp[temp.length - 1]); // it's 2
Edit
You might want to check if your number is an actual decimal, you can do:
var temp = myNum.toString();
if(/\d+(\.\d+)?/.test(temp)) {
var lastNum = parseInt(temp[temp.length - 1]);
// do the rest
}
This approach:
var regexp = /\..*(\d)$/;
var matches = "123.456".match(reg);
if (!matches) { alert ("no decimal point or following digits"); }
else alert(matches[1]);
How this works:
\. : matches decimal point
.* : matches anything following decimal point
(\d) : matches digit, and captures it
$ : matches end of string
As pointed out in comments, I initially misunderstood your question and thought you wanted the FIRST digit after the decimal place, which is what this one-liner does:
result = Math.floor((myNum - Math.floor(myNum)) * 10);
If you want a purely mathematical solution that gives you the LAST digit after the decimal place you can transform the number until the last digit is the first one after the decimal place and THEN use the above code, like this (but it's no longer a nice one-liner):
temp = myNum;
while( Math.floor(temp) != temp ) temp *= 10;
temp /= 10;
result = Math.floor((temp- Math.floor(temp)) * 10);
How it works:
the above code multiplies temp by 10 until there is nothing after the decimal place, then divides by 10 to yield a number with only a single digit after the decimal place then uses my original code to give you the first digit after the decimal place! Phew!
Just do:
function lastdigit(a)
{
return a % 10;
}
Below is my JavaScript:
var s = new Number(123456789);
alert(s.toLocaleString("en-US"));
this gives result 123,456,789 in chrome. But IE 8 shows 123,456,789.00. Is there any workaround to restrict the addition of ".00" in IE?
FYI: I have already checked This which gives problem in Chrome and have searched around google with no use.
// Following #RobG's comment I have altered and simplified to find any character that might be used as a decimal point (unless it's the first character)
var s = new Number(123456789);
var s1 = s.toLocaleString();
var p = new Number(Math.floor(s) + 0.1); // similar value but decimal
var p1 = p.toLocaleString();
var index;
var point;
for (index=p1.length-1; index>0; index--) { // find decimal point in dummy
point = p1.charAt(index);
if (point < '0' || point > '9')
break;
}
if (index > 0) {
index = s1.lastIndexOf(point); // find last point in string
if (index > 0)
s1 = s1.slice(0, index); // truncate decimal part
}
alert(s1);
You can test for the decimal separator and remove it and everything thereafter:
// Work out whether decimal separator is . or , for localised numbers
function getDecimalSeparator() {
return /\./.test((1.1).toLocaleString())? '.' : ',';
}
// Round n to an integer and present
function myToLocaleInteger(n) {
var re = new RegExp( '\\' + getDecimalSeparator() + '\\d+$');
return Math.round(n).toLocaleString().replace(re,'');
}
// Test with a number that has decimal places
var n = 12345.99
console.log(n.toLocaleString() + ' : ' + myToLocaleInteger(n)); // 12,345.99 : 12,346
You'll need to change system settings to test thoroughly.
Edit
If you want to change the built–in toLocaleString, try:
// Only modify if toLocaleString adds decimal places
if (/\D/.test((1).toLocaleString())) {
Number.prototype.toLocaleString = (function() {
// Store built-in toLocaleString
var _toLocale = Number.prototype.toLocaleString;
// Work out the decimal separator
var _sep = /\./.test((1.1).toLocaleString())? '.' : ',';
// Regular expression to trim decimal places
var re = new RegExp( '\\' + _sep + '\\d+$');
return function() {
// If number is an integer, call built–in function and trim decimal places
// if they're added
if (parseInt(this) == this) {
return _toLocale.call(this).replace(re,'');
}
// Otherwise, just convert to locale
return _toLocale.call(this);
}
}());
}
This will modify the built–in toLocaleString only if it adds decimal places to integers.
I'm trying to do frame by frame animation in html5, but the outputted files are numbered automatically like so 00010, 00011 etc..
var imgNumber = 00001;
var lastImgNumber = 00200;
Using the above and trying to increase the value by 1 removes the leading zeros. Perhaps, I can count how many digits are in the number, and depending on how many I can concatenate the extra zeros as a string?
What's the best way of approaching this?
If you convert a number to a string you can count the number of digits.
function padNum(num, digits){
var str = num + "";
return num.length >= digits? str: padNum("0" + str, digits);
}
padNum(1, 4) => "0001";
padNum(34, 4) => "0034";
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.