Javascript restrict input once 2 decimal places have been reached - javascript

I currently have a number input script that behaves similar to a calculator with the way numbers are displayed, but I want to stop the adding of additional numbers to the series after two numbers past the decimal point.
Here is what I have so far, though the limiting doesn't occur correctly.
It should work like this:
1.25 - Allowed
12.5 - Allowed
125.5 - Allowed
125.55 - Allowed
123.555 - Not Allowed
rText = document.getElementById("resultText");
function selectNumber(num) {
if (!rText.value || rText.value == "0") {
rText.value = num;
}
else {
this part works...
rText.value += num;
}
}
}
but this part doesn't work... Any ideas???
if (rText.value.length - (rText.value.indexOf(".") + 1) > 2) {
return false;
} else {
rText.value += num;
}
}
}

var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
<input type="text" id="resultText" oninput="validate(this)" />

Save the previous value in some data attribute and if it exceeds 2 decimal places then restore the previous value
The 2 decimal places can be checked using Math.round(tis.value*100)/100!=tis.value
Note:
I have used oninputto validate even in copy paste scenarios
function restrict(tis) {
var prev = tis.getAttribute("data-prev");
prev = (prev != '') ? prev : '';
if (Math.round(tis.value*100)/100!=tis.value)
tis.value=prev;
tis.setAttribute("data-prev",tis.value)
}
<input type="number" id="rText" oninput="restrict(this);" />

I love to use Math.floor and toFixed() to resolve my decimal issues.
Here is a example:
var value = 123.5555
var roundedNumber = (Math.floor(value * 100) / 100).toFixed(2)
roundedNumber will be "123.55" as a string. So if you want as a number just add:
var value = 123.5555
var roundedNumber = Number((Math.floor(value * 100) / 100).toFixed(2))
and now you have value as a number and fixed to up 2 decimal places.

Just copy paste this method and call this method on your respective button on which button you have to check this decimal validation.
function CheckDecimal(inputtxt)
{
var decimal= /^[-+]?[0-9]+\.[0-9]+$/;
if(inputtxt.value.match(decimal))
{
alert('Correct, try another...')
return true;
}
else
{
alert('Wrong...!')
return false;
}
}

Related

HTML5 number input - display as percentage instead of decimal

I have a form including number inputs which are supposed to represent percentages, which are set up approximately like below:
<input type="number" min="0" max="1" step="0.01" />
Currently, the values show up as decimals, for example, 0.25. I think it'd be a lot more user-friendly if the number displayed in the text field showed up as a percentage instead. I've already disabled keyboard input on the field using the below jQuery code, so I'm not worried about users inputting rogue values:
$('input[type="number"]').keypress(function (field) {
field.preventDefault();
});
Is there an easy way to change the number fields to display a percentage?
Thank you!
There are two ways which I hope will work.
If you want percentages in input and need to convert it to decimals in js then:
<input type="number" min="1" max="100" id="myPercent"/>
in js:
document.getElementById('myForm').onsubmit = function() {
var valInDecimals = document.getElementById('myPercent').value / 100;
}
If scenario is reverse then:
<input type="number" min="0" max="1" step="0.01" id="myPercent"/>
in js:
document.getElementById('myForm').onsubmit = function() {
var valInDecimals = document.getElementById('myPercent').value * 100;
}
While not a HTML5 input type='number', the solution bellow uses input type='text' to the same effect. The rational of not using type='number' being humans require a nicely formatted string like "23.75%" while robots prefer to read integers and floating points should be avoided. The snippet bellow does just that to 2 decimal places.
I haven't tested it on a mobile, but I think the number pad should appear as with input type='number'.
Codepen.io: Commented code can be found here
document.querySelector('.percent').addEventListener('input', function(e) {
let int = e.target.value.slice(0, e.target.value.length - 1);
if (int.includes('%')) {
e.target.value = '%';
} else if (int.length >= 3 && int.length <= 4 && !int.includes('.')) {
e.target.value = int.slice(0, 2) + '.' + int.slice(2, 3) + '%';
e.target.setSelectionRange(4, 4);
} else if (int.length >= 5 & int.length <= 6) {
let whole = int.slice(0, 2);
let fraction = int.slice(3, 5);
e.target.value = whole + '.' + fraction + '%';
} else {
e.target.value = int + '%';
e.target.setSelectionRange(e.target.value.length - 1, e.target.value.length - 1);
}
console.log('For robots: ' + getInt(e.target.value));
});
function getInt(val) {
let v = parseFloat(val);
if (v % 1 === 0) {
return v;
} else {
let n = v.toString().split('.').join('');
return parseInt(n);
}
}
<input class="percent" type="text" value="23.75%" maxlength="6">
Maybe add a function, the outputted number (for example 0.25) * 100 + "%", on this way you always have it in percents.
function topercentage() {
var outputnumber = outputnumber * 100 + "%";
}
In this example outputnumber is the number for example 0.25. I hope this works.

Javascript String indexOf not working as expected

I must be missing something .. not sure why my JavaScript is failing or not working
var discount = 10;
var newTemp;
if (discount != null) {
if (discount.indexOf("%") > -1) {
newTemp = discount.substring(0, 2) + '%';
} else {
newTemp = discount;
}
} //end of outer if
Above script works when discount = "10.0%"
But fails when discount = 10
maynot be best way, but all I am trying to do is if discount value contains % sign then setting newTemp variable with new value. Else just keep it as is.
Any idea, why control fails when discount value is = 10
because "10%" is a string, therefore it has a indexOf method, and 10 is probably an integer or number.
Try discount.toString().indexOf('%')
It's because you're not appending the '%' in the else branch.
var newTemp;
if (discount != null) {
if (discount.indexOf("%") > -1) {
newTemp = discount.substring(0, 2);
} else {
newTemp = discount;
}
} //end of outer if
newTemp += '%';
also as Hugo said, the number 10 does not have the indexOf method, which is a string method.

Javascript rounding failure

This is the rounding function we are using (which is taken from stackoverflow answers on how to round). It rounds half up to 2dp (by default)
e.g. 2.185 should go to 2.19
function myRound(num, places) {
if (places== undefined) {
// default to 2dp
return Math.round(num* 100) / 100;
}
var mult = Math.pow(10,places);
return Math.round(num* mult) / mult;
}
It has worked well but now we have found some errors in it (in both chrome and running as jscript classic asp on IIS 7.5).
E.g.:
alert(myRound(2.185)); // = 2.19
alert (myRound(122.185)); // = 122.19
alert (myRound(511.185)); // = 511.19
alert (myRound(522.185)); // = 522.18 FAIL!!!!
alert (myRound(625.185)); // = 625.18 FAIL!!!!
Does anyone know:
Why this happens.
How we can round half up to 2 dp without random rounding errors like this.
update: OK, the crux of the problem is that in js, 625.185 * 100 = 62518.499999
How can we get over this?
Your problem is not easily resolved. It occurs because IEEE doubles use a binary representation that cannot exactly represent all decimals. The closest internal representation to 625.185 is 625.18499999999994543031789362430572509765625, which is ever so slightly less than 625.185, and for which the correct rounding is downwards.
Depending on your circumstances, you might get away with the following:
Math.round(Math.round(625.185 * 1000) / 10) / 100 // evaluates to 625.19
This isn't strictly correct, however, since, e.g., it will round, 625.1847 upwards to 625.19. Only use it if you know that the input will never have more than three decimal places.
A simpler option is to add a small epsilon before rounding:
Math.round(625.185 * 100 + 1e-6) / 100
This is still a compromise, since you might conceivably have a number that is very slightly less than 625.185, but it's probably more robust than the first solution. Watch out for negative numbers, though.
Try using toFixed function on value.
example is below:
var value = parseFloat(2.185);
var fixed = value.toFixed(2);
alert(fixed);
I tried and it worked well.
EDIT: You can always transform string to number using parseFloat(stringVar).
EDIT2:
function myRound(num, places) {
return parseFloat(num.toFixed(places));
}
EDIT 3:
Updated answer, tested and working:
function myRound(num, places) {
if (places== undefined) {
places = 2;
}
var mult = Math.pow(10,places + 1);
var mult2 = Math.pow(10,places);
return Math.round(num* mult / 10) / mult2;
}
EDIT 4:
Tested on most examples noted in comments:
function myRound(num, places) {
if (places== undefined) {
places = 2;
}
var mult = Math.pow(10,places);
var val = num* mult;
var intVal = parseInt(val);
var floatVal = parseFloat(val);
if (intVal < floatVal) {
val += 0.1;
}
return Math.round(val) / mult;
}
EDIT 5:
Only solution that I managed to find is to use strings to get round on exact decimal.
Solution is pasted below, with String prototype extension method, replaceAt.
Please check and let me know if anyone finds some example that is not working.
function myRound2(num, places) {
var retVal = null;
if (places == undefined) {
places = 2;
}
var splits = num.split('.');
if (splits && splits.length <= 2) {
var wholePart = splits[0];
var decimalPart = null;
if (splits.length > 1) {
decimalPart = splits[1];
}
if (decimalPart && decimalPart.length > places) {
var roundingDigit = parseInt(decimalPart[places]);
var previousDigit = parseInt(decimalPart[places - 1]);
var increment = (roundingDigit < 5) ? 0 : 1;
previousDigit = previousDigit + increment;
decimalPart = decimalPart.replaceAt(places - 1, previousDigit + '').substr(0, places);
}
retVal = parseFloat(wholePart + '.' + decimalPart);
}
return retVal;
}
String.prototype.replaceAt = function (index, character) {
return this.substr(0, index) + character + this.substr(index + character.length);
}
OK, found a "complete" solution to the issue.
Firstly, donwnloaded Big.js from here: https://github.com/MikeMcl/big.js/
Then modified the source so it would work with jscript/asp:
/* big.js v2.1.0 https://github.com/MikeMcl/big.js/LICENCE */
var Big = (function ( global ) {
'use strict';
:
// EXPORT
return Big;
})( this );
Then did my calculation using Big types and used the Big toFixed(dp), then converted back into a number thusly:
var bigMult = new Big (multiplier);
var bigLineStake = new Big(lineStake);
var bigWin = bigLineStake.times(bigMult);
var strWin = bigWin.toFixed(2); // this does the rounding correctly.
var win = parseFloat(strWin); // back to a number!
This basically uses Bigs own rounding in its toFixed, which seems to work correctly in all cases.
Shame Big doesnt have a method to convert back to a number without having to go through a string.

Round number up to the nearest multiple of 3

How would I go about rounded a number up the nearest multiple of 3?
i.e.
25 would return 27
1 would return 3
0 would return 3
6 would return 6
if(n > 0)
return Math.ceil(n/3.0) * 3;
else if( n < 0)
return Math.floor(n/3.0) * 3;
else
return 3;
Simply:
3.0*Math.ceil(n/3.0)
?
Here you are!
Number.prototype.roundTo = function(num) {
var resto = this%num;
if (resto <= (num/2)) {
return this-resto;
} else {
return this+num-resto;
}
}
Examples:
y = 236.32;
x = y.roundTo(10);
// results in x = 240
y = 236.32;
x = y.roundTo(5);
// results in x = 235
I'm answering this in psuedocode since I program mainly in SystemVerilog and Vera (ASIC HDL). % represents a modulus function.
round_number_up_to_nearest_divisor = number + ((divisor - (number % divisor)) % divisor)
This works in any case.
The modulus of the number calculates the remainder, subtracting that from the divisor results in the number required to get to the next divisor multiple, then the "magic" occurs. You would think that it's good enough to have the single modulus function, but in the case where the number is an exact multiple of the divisor, it calculates an extra multiple. ie, 24 would return 27. The additional modulus protects against this by making the addition 0.
As mentioned in a comment to the accepted answer, you can just use this:
Math.ceil(x/3)*3
(Even though it does not return 3 when x is 0, because that was likely a mistake by the OP.)
Out of the nine answers posted before this one (that have not been deleted or that do not have such a low score that they are not visible to all users), only the ones by Dean Nicholson (excepting the issue with loss of significance) and beauburrier are correct. The accepted answer gives the wrong result for negative numbers and it adds an exception for 0 to account for what was likely a mistake by the OP. Two other answers round a number to the nearest multiple instead of always rounding up, one more gives the wrong result for negative numbers, and three more even give the wrong result for positive numbers.
This function will round up to the nearest multiple of whatever factor you provide.
It will not round up 0 or numbers which are already multiples.
round_up = function(x,factor){ return x - (x%factor) + (x%factor>0 && factor);}
round_up(25,3)
27
round up(1,3)
3
round_up(0,3)
0
round_up(6,3)
6
The behavior for 0 is not what you asked for, but seems more consistent and useful this way. If you did want to round up 0 though, the following function would do that:
round_up = function(x,factor){ return x - (x%factor) + ( (x%factor>0 || x==0) && factor);}
round_up(25,3)
27
round up(1,3)
3
round_up(0,3)
3
round_up(6,3)
6
Building on #Makram's approach, and incorporating #Adam's subsequent comments, I've modified the original Math.prototype example such that it accurately rounds negative numbers in both zero-centric and unbiased systems:
Number.prototype.mround = function(_mult, _zero) {
var bias = _zero || false;
var base = Math.abs(this);
var mult = Math.abs(_mult);
if (bias == true) {
base = Math.round(base / mult) * _mult;
base = (this<0)?-base:base ;
} else {
base = Math.round(this / _mult) * _mult;
}
return parseFloat(base.toFixed(_mult.precision()));
}
Number.prototype.precision = function() {
if (!isFinite(this)) return 0;
var a = this, e = 1, p = 0;
while (Math.round(a * e) / e !== a) { a *= 10; p++; }
return p;
}
Examples:
(-2).mround(3) returns -3;
(0).mround(3) returns 0;
(2).mround(3) returns 3;
(25.4).mround(3) returns 24;
(15.12).mround(.1) returns 15.1
(n - n mod 3)+3
$(document).ready(function() {
var modulus = 3;
for (i=0; i < 21; i++) {
$("#results").append("<li>" + roundUp(i, modulus) + "</li>")
}
});
function roundUp(number, modulus) {
var remainder = number % modulus;
if (remainder == 0) {
return number;
} else {
return number + modulus - remainder;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Round up to nearest multiple of 3:
<ul id="results">
</ul>
A more general answer that might help somebody with a more general problem: if you want to round numbers to multiples of a fraction, consider using a library. This is a valid use case in GUI where decimals are typed into input and for instance you want to coerce them to multiples of 0.25, 0.2, 0.5 etc. Then the naive approach won't get you far:
function roundToStep(value, step) {
return Math.round(value / step) * step;
}
console.log(roundToStep(1.005, 0.01)); // 1, and should be 1.01
After hours of trying to write up my own function and looking up npm packages, I decided that Decimal.js gets the job done right away. It even has a toNearest method that does exactly that, and you can choose whether to round up, down, or to closer value (default).
const Decimal = require("decimal.js")
function roundToStep (value, step) {
return new Decimal(value).toNearest(step).toNumber();
}
console.log(roundToStep(1.005, 0.01)); // 1.01
RunKit example
Using remainder operator (modulus):
(n - 1 - (n - 1) % 3) + 3
By the code given below use can change any numbers and you can find any multiple of any number
let numbers = [8,11,15];
let multiple = 3
let result = numbers.map(myFunction);
function myFunction(n){
let answer = Math.round(n/multiple) * multiple ;
if (answer <= 0)
return multiple
else
return answer
}
console.log("Closest Multiple of " + multiple + " is " + result);
if(x%3==0)
return x
else
return ((x/3|0)+1)*3

Problem with JavaScript arithmetic

I have a form for my customers to add budget projections. A prominent user wants to be able to show dollar values in either dollars, Kila-dollars or Mega-dollars.
I'm trying to achieve this with a group of radio buttons that call the following JavaScript function, but am having problems with rounding that make the results look pretty crummy.
Any advice would be much appreciated!
Lynn
function setDollars(new_mode)
{
var factor;
var myfield;
var myval;
var cur_mode = document.proj_form.cur_dollars.value;
if(cur_mode == new_mode)
{
return;
}
else if((cur_mode == 'd')&&(new_mode == 'kd'))
{
factor = "0.001";
}
else if((cur_mode == 'd')&&(new_mode == 'md'))
{
factor = "0.000001";
}
else if((cur_mode == 'kd')&&(new_mode == 'd'))
{
factor = "1000";
}
else if((cur_mode == 'kd')&&(new_mode == 'md'))
{
factor = "0.001";
}
else if((cur_mode == 'md')&&(new_mode == 'kd'))
{
factor = "1000";
}
else if((cur_mode == 'md')&&(new_mode == 'd'))
{
factor = "1000000";
}
document.proj_form.cur_dollars.value = new_mode;
var cur_idx = document.proj_form.cur_idx.value;
var available_slots = 13 - cur_idx;
var td_name;
var cell;
var new_value;
//Adjust dollar values for projections
for(i=1;i<13;i++)
{
var myfield = eval('document.proj_form.proj_'+i);
if(myfield.value == '')
{
myfield.value = 0;
}
var myval = parseFloat(myfield.value) * parseFloat(factor);
myfield.value = myval;
if(i < cur_idx)
{
document.getElementById("actual_"+i).innerHTML = myval;
}
}
First of all, Don't set myfield.value = myval after doing the math. You'll accumulate rounding errors with each additional selection of one of the radio buttons. Keep myfield.value as dollars all the time, then calculate a display value. This will also reduce the number of cases in your if-else cascade, as you will always be converting from dollars.
Now calculate by division -- you'll never have to multiply by 0.001 or 1000 since you're always converting in the same direction.
Use Math.round() to control rounding errors. You can multiply your original value first, then divide by a larger factor to also help control rounding errors; e.g. both these are the same in pure mathematics:
newvalue = value / 1000;
newvalue = (value * 10) / 10000;
Added
switch (new_mode)
{
case 'd':
divisor = 1;
break;
case 'kd':
divisor = 1000;
break;
case 'md':
divisor = 1000000;
break;
}
var displayValue = myfield.value / divisor;
Also, don't assign a string of numbers divisor = "1000"; use actual numbers divisor = 1000 (without the quotes)
Javascript's floating point numbers are a constant source of irritation.
You should try adding toFixed() to reduce the inevitable absurd decimals, and I've actually had to resort to forcing it to do it's rounding down where I don't care about it by doing something like:
number_to_be_rounded = Math.round(number_to_be_rounded*1000)/1000;
number_to_be_rounded = parseFloat(number_to_be_rounded.toFixed(2));
It's ugly, but it's close enough for a non-financial system.

Categories

Resources