How would I go about changing this code so that the number 7 can be replaced with any number between 7 and 16?
var lvalue = $( ".leave-input" ).val();
if (lvalue <= 7.29) {
lvalue = roundDown();
} else if (lvalue >= 7.3) {
lvalue = roundUp();
}
I am trying to round the time the user input ups the nearest hour. I had trouble using time so am now just using the number they input.
To clarify rather then having an if statement for each number, 7, 8, 9 etc. Is there a way to rewrite the current code so "7" can be any number between 7 and 16?
If you add 0.2 to the value, you can use Math.round():
input.oninput = function() {
let lvalue = +document.getElementById('input').value + 0.2;
document.getElementById('output').innerHTML = Math.round(lvalue);
}
<input id="input" type="text">
<div id="output"></div>
You can make it so that the number is smaller than 1, then it should work for all cases:
let lvalue = $(".leave-input").val();
const baseValue = Math.round((lvalue - Math.floor(lvalue)) * 100) / 100;
if (baseValue<= 0.29) {
lvalue = roundDown();
} else if (baseValue>= 0.3) {
lvalue = roundUp();
}
Here is a working example:
function calculate() {
let lvalue = Number(document.getElementById('input').value)
const baseValue = Math.round((lvalue - Math.floor(lvalue)) * 100) / 100;
if (baseValue <= 0.29) {
lvalue = Math.floor(lvalue);
} else if (baseValue >= 0.3) {
lvalue = Math.ceil(lvalue);
}
document.getElementById('output').innerHTML = lvalue;
}
<input id="input" type="text" />
<button onClick="calculate()">Round</button>
<div id="output"></div>
let lvalue = $(".leave-input").val();
const integer = Math.trunc(lvalue);
const decimal = lvalue % 1;// or you could do lvalue - interger
if (integer >= 7 && integer <= 16) {
if (decimal <= 0.29) {
lvalue = roundDown();
} else if (decimal >= 0.3) {
lvalue = roundUp();
}
}
$(".leave-input").change(function(){
let lvalue = parseFloat($(".leave-input").val());
const val = lvalue * 100 % 100 ;
if (val <= 29) {
lvalue = Math.floor(lvalue);//roundDown();
} else {//your condition will skip anything between .29 and .30
lvalue = Math.ceil(lvalue);//roundUp();
}
$(".result").html(lvalue);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="leave-input" />
<div class="result"></div>
Related
I have a signed value given as a hex number, by example 0xffeb and want convert it into -21 as a "normal" Javascript integer.
I have written some code so far:
function toBinary(a) { //: String
var r = '';
var binCounter = 0;
while (a > 0) {
r = a%2 + r;
a = Math.floor(a/2);
}
return r;
}
function twoscompl(a) { //: int
var l = toBinaryFill(a).length;
var msb = a >>> (l-1);
if (msb == 0) {
return a;
}
a = a-1;
var str = toBinary(a);
var nstr = '';
for (var i = 0; i < str.length; i++) {
nstr += str.charAt(i) == '1' ? '0' : '1';
}
return (-1)*parseInt(nstr);
}
The problem is, that my function returns 1 as MSB for both numbers because only at the MSB of the binary representation "string" is looked. And for this case both numbers are 1:
-21 => 0xffeb => 1111 1111 1110 1011
21 => 0x15 => 1 0101
Have you any idea to implement this more efficient and nicer?
Greetings,
mythbu
Use parseInt() to convert (which just accepts your hex string):
parseInt(a);
Then use a mask to figure out if the MSB is set:
a & 0x8000
If that returns a nonzero value, you know it is negative.
To wrap it all up:
a = "0xffeb";
a = parseInt(a, 16);
if ((a & 0x8000) > 0) {
a = a - 0x10000;
}
Note that this only works for 16-bit integers (short in C). If you have a 32-bit integer, you'll need a different mask and subtraction.
I came up with this
function hexToInt(hex) {
if (hex.length % 2 != 0) {
hex = "0" + hex;
}
var num = parseInt(hex, 16);
var maxVal = Math.pow(2, hex.length / 2 * 8);
if (num > maxVal / 2 - 1) {
num = num - maxVal
}
return num;
}
And usage:
var res = hexToInt("FF"); // -1
res = hexToInt("A"); // same as "0A", 10
res = hexToInt("FFF"); // same as "0FFF", 4095
res = hexToInt("FFFF"); // -1
So basically the hex conversion range depends on hex's length, ant this is what I was looking for. Hope it helps.
Based on #Bart Friederichs I've come with:
function HexToSignedInt(num, numSize) {
var val = {
mask: 0x8 * Math.pow(16, numSize-1), // 0x8000 if numSize = 4
sub: -0x1 * Math.pow(16, numSize) //-0x10000 if numSize = 4
}
if((parseInt(num, 16) & val.mask) > 0) { //negative
return (val.sub + parseInt(num, 16))
}else { //positive
return (parseInt(num,16))
}
}
so now you can specify the exact length (in nibbles).
var numberToConvert = "CB8";
HexToSignedInt(numberToConvert, 3);
//expected output: -840
function hexToSignedInt(hex) {
if (hex.length % 2 != 0) {
hex = "0" + hex;
}
var num = parseInt(hex, 16);
var maxVal = Math.pow(2, hex.length / 2 * 8);
if (num > maxVal / 2 - 1) {
num = num - maxVal
}
return num;
}
function hexToUnsignedInt(hex){
return parseInt(hex,16);
}
the first for signed integer and
the second for unsigned integer
As I had to turn absolute numeric values to int32 values that range from -2^24 to 2^24-1,
I came up with this solution, you just have to change your input into a number through parseInt(hex, 16), in your case, nBytes is 2.
function toSignedInt(value, nBytes) { // 0 <= value < 2^nbytes*4, nBytes >= 1,
var hexMask = '0x80' + '00'.repeat(nBytes - 1);
var intMask = parseInt(hexMask, 16);
if (value >= intMask) {
value = value - intMask * 2;
}
return value;
}
var vals = [ // expected output
'0x00', // 0
'0xFF', // 255
'0xFFFFFF', // 2^24 - 1 = 16777215
'0x7FFFFFFF', // 2^31 -1 = 2147483647
'0x80000000', // -2^31 = -2147483648
'0x80000001', // -2^31 + 1 = -2147483647
'0xFFFFFFFF', // -1
];
for (var hex of vals) {
var num = parseInt(hex, 16);
var result = toSignedInt(num, 4);
console.log(hex, num, result);
}
var sampleInput = '0xffeb';
var sampleResult = toSignedInt(parseInt(sampleInput, 16), 2);
console.log(sampleInput, sampleResult); // "0xffeb", -21
Based on the accepted answer, expand to longer number types:
function parseSignedShort(str) {
const i = parseInt(str, 16);
return i >= 0x8000 ? i - 0x10000 : i;
}
parseSignedShort("0xffeb"); // -21
function parseSignedInt(str) {
const i = parseInt(str, 16);
return i >= 0x80000000 ? i - 0x100000000 : i;
}
parseSignedInt("0xffffffeb"); // -21
// Depends on new JS feature. Only supported after ES2020
function parseSignedLong(str) {
if (!str.toLowerCase().startsWith("0x"))
str = "0x" + str;
const i = BigInt(str);
return Number(i >= 0x8000000000000000n ? i - 0x10000000000000000n : i);
}
parseSignedLong("0xffffffffffffffeb"); // -21
I have a code that is inserting the total value into a textbox, however, the math that is performed does not round the number. Based on the code below how can I make this happen?
function calculate(){
var mrc = document.getElementById('box1');
var days = document.getElementById('box2');
var total = document.getElementById('box3');
var reason = document.getElementById('box4');
var approver = document.getElementById('box5');
var approvalreason = document.getElementById('box6');
var custname = document.getElementById('box7');
var caseid = document.getElementById('box8');
var intermitent = document.getElementById('rb1');
var outage = document.getElementById('rb2');
if (outage.checked === true) {
if (days.value * 5 > mrc.value){
total.value = (mrc.value / 30) * days.value;
} else if (days.value > 14) {
total.value = (mrc.value / 30) * days.value;
} else {
total.value = days.value * 5;
}
} else if (intermitent.checked === true){
if (days.value * 3 > mrc.value)
{
total.value = (mrc.value / 30) * days.value;
} else if (days.value > 14) {
total.value = (mrc.value / 30) * days.value;
} else {
total.value = days.value * 3;
}
}
}
Two things:
You're playing with fire by using implicit type conversion. element.value returns a string, not a number, so you should be using parseInt() or parseFloat() to convert your values to numbers. For instance, if your input has value 3, and you do element.value + 2, the result is 32.
Second, to your question, Math.ceil() rounds a float up to the near integer.
Use round() method to rounds a number to the nearest integer.
Example:
var a = Math.round(8.70);
Answer a = 9;
Try the following code:
function toFixed(value, precision) {
var precision = precision || 0,
power = Math.pow(10, precision),
absValue = Math.abs(Math.round(value * power)),
result = (value < 0 ? '-' : '') + String(Math.floor(absValue / power));
if (precision > 0) {
var fraction = String(absValue % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
result += '.' + padding + fraction;
}
return result;
}
alert(toFixed(1.0000000,3));
Following is the fiddle link:
Demo
I have Float32Array textures which can be displayed through WebGL correctly. However, when I tried to convert them into Uint16Array, the problem occurs.
Here is my conversion part.
var _floatToHalfFloat = function(input, offset) {
var largestHalf = Math.pow(2, 30-15) * (1 + 1023/1024);
var m = new ArrayBuffer(4);
var n = new Float32Array(m);
var o = new Uint32Array(m);
var f = 0.0;
for (var i = input.length - 1 - offset; i >= 0;i--) {
n[0] = input[i];
f = o[0];
// fast conversion of half
// ref : ftp://www.fox-toolkit.org/pub/fasthalffloatconversion.pdf
if (isNaN(input[i])) {
input[i] = 0x7fff;
} else if(n === Infinity || n > largestHalf) {
input[i] = 0x7c00;
} else if(n === -Infinity || n < -largestHalf) {
input[i] = 0xfc00;
} else if(n === 0) {
input[i] = 0;
} else {
input[i] = ((f>>16)&0x8000)|((((f&0x7f800000)-0x38000000)>>13)&0x7c00)|((f>>13)&0x03ff);
}
}
return new Uint16Array(input);
};
We can see saturated colors (full red, green and/or blue) in the converted image when reaching black color in the original image. I think the function doesn't work very well near 0.
I have done a quick implementation of wikipedia explanation of norm of the float 16 bits.
<html>
<head>
<script>
var _floatToHalfFloat = #### YOUR FUNCTION HERE CUT ####
var _halfFloatToFloat = function(hf) {
var m = new ArrayBuffer(2);
var n = new Uint16Array(m);
n[0] = hf;
var sign = n[0] & 0x8000;
var exp = (n[0] >> 10) & 0x1F;
var mant = n[0]& 0x03FF;
document.getElementById('sign').innerHTML += sign+" - ";
document.getElementById('exp').innerHTML += exp+" - ";
document.getElementById('mant').innerHTML += mant+" - ";
if (exp == 0x1F) {
return 1.0 * Math.pow(-1, sign) * Infinity;
} else if (exp == 0) {
return Math.pow(-1, sign) *
Math.pow(2, -14) *
(mant / Math.pow(2, 10));
} else {
return Math.pow(-1, sign) *
Math.pow(2, exp-15) *
(1+(mant / Math.pow(2, 10)));
}
};
document.addEventListener("DOMContentLoaded", function(event) {
var input = new Float32Array(8);
input[0] = 2.5;
input[1] = 0.25;
input[2] = 0.025;
input[3] = 0.025;
input[4] = 0.0025;
input[5] = 0.00025;
input[6] = 0.000025;
input[7] = 0.0;
var i, s = "Value before = ";
for (i = 0; i < input.length; i++)
s += input[i] + " - ";
document.getElementById('res1').innerHTML = s;
var output = _floatToHalfFloat(input, 0);
s = "Value after = ";
for (i = 0; i < output.length; i++)
s += _halfFloatToFloat(output[i]) + " - ";
document.getElementById('res2').innerHTML = s;
});
</script>
</head>
<body>
<span id="res1">result</span></br>
<span id="res2">result</span></br>
</br></br></br>
<span id="sign">signs =</span></br>
<span id="exp">exponents =</span></br>
<span id="mant">mantissas =</span></br>
</body>
</html>
The test results are shown below :
Value before = 2.5 - 0.25 - 0.02500000037252903 - 0.02500000037252903 - 0.0024999999441206455 - 0.0002500000118743628 - 0.00002499999936844688 - 0 -
Value after = 2.5 - 0.25 - 0.024993896484375 - 0.024993896484375 - 0.002498626708984375 - 0.0002498626708984375 - Infinity - 2 -
signs =0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 -
exponents =16 - 13 - 9 - 9 - 6 - 3 - 31 - 16 -
mantissas =256 - 0 - 614 - 614 - 286 - 24 - 653 - 0 -
This shows that the 2 last information are not coherent. 0.000025 is transformed into Infinity (rather than 0?) and 0 itself is transformed to 2. This doesn't appear to be correct. When you want to code a zero "wikipedia says" your mantissa AND your exponent should be zero. In the code you provided the mantissa is zero but the exponent is 16 which leads to 2 (2^(16-15)).
After tweaking a bit your function it appears that all cases are treated as normal one. This is due to a bug in your if statements. So instead of having :
} else if(n === 0) {
input[i] = 0;
}
You want probably do something like that :
} else if(n[0] === 0) {
input[i] = 0;
}
And the same for all uses of n variable. But you still have the underflow problem.So may be you can find acceptable to do :
} else if(Math.abs(n[0]) < 0.0001) {
input[i] = 0;
}
I have code that converts pixels into inches. But the result is a decimal.
How can I have the result return a fraction for the inch, example: 1/4 instead of .25
Here is the HTML:
<label>Pixels</label>
<input class="calcd" id="calc3" type="text" />
<input class="calcd" id="calc4" type="hidden" value="96" />
<br />Inches <span id="result2"></span>
Here is the Jquery:
$(document).ready(function(){
$(".calcd").keyup(function(){
var val1 = parseInt($("#calc3").val());
var val2 = parseInt($("#calc4").val());
if ( ! isNaN(val1) && ! isNaN(val2))
{
$("#result2").text((val1 / val2).toFixed(2));
}
});
});
I see this here on stackoverflow:
where using the var decimal = eval(fraction); will work, but am confused on it.
Here is the JsFiddle
2 options you got:
Working demo =>: http://jsfiddle.net/Nn2yq/ -- Convert a decimal number to a fraction / rational number
you can use this: https://github.com/ekg/fraction.js
Also you only need one $(document).ready(function () {
hope this helps. :)
COde
$(document).ready(function () {
$(".calc").keyup(function () {
var val1 = parseInt($("#calc1").val());
var val2 = parseInt($("#calc2").val());
if (!isNaN(val1) && !isNaN(val2)) {
$("#result").text(val1 * val2);
}
});
$(".calcd").keyup(function () {
var val1 = parseInt($("#calc3").val());
var val2 = parseInt($("#calc4").val());
if (!isNaN(val1) && !isNaN(val2)) {
$("#result2").text(fraction((val1 / val2).toFixed(2)));
}
});
});
//convert a decimal into a fraction
function fraction(decimal) {
if (!decimal) {
decimal = this;
}
whole = String(decimal).split('.')[0];
decimal = parseFloat("." + String(decimal).split('.')[1]);
num = "1";
for (z = 0; z < String(decimal).length - 2; z++) {
num += "0";
}
decimal = decimal * num;
num = parseInt(num);
for (z = 2; z < decimal + 1; z++) {
if (decimal % z == 0 && num % z == 0) {
decimal = decimal / z;
num = num / z;
z = 2;
}
}
//if format of fraction is xx/xxx
if (decimal.toString().length == 2 && num.toString().length == 3) {
//reduce by removing trailing 0's
decimal = Math.round(Math.round(decimal) / 10);
num = Math.round(Math.round(num) / 10);
}
//if format of fraction is xx/xx
else if (decimal.toString().length == 2 && num.toString().length == 2) {
decimal = Math.round(decimal / 10);
num = Math.round(num / 10);
}
//get highest common factor to simplify
var t = HCF(decimal, num);
//return the fraction after simplifying it
return ((whole == 0) ? "" : whole + " ") + decimal / t + "/" + num / t;
}
function HCF(u, v) {
var U = u,
V = v
while (true) {
if (!(U %= V)) return V
if (!(V %= U)) return U
}
}
working screenshot
I have a number assigned to a variable, like that:
var myVar = 1234;
Now I want to get the second digit (2 in this case) from that number without converting it to a string first. Is that possible?
So you want to get the second digit from the decimal writing of a number.
The simplest and most logical solution is to convert it to a string :
var digit = (''+myVar)[1];
or
var digit = myVar.toString()[1];
If you don't want to do it the easy way, or if you want a more efficient solution, you can do that :
var l = Math.pow(10, Math.floor(Math.log(myVar)/Math.log(10))-1);
var b = Math.floor(myVar/l);
var digit = b-Math.floor(b/10)*10;
Demonstration
For people interested in performances, I made a jsperf. For random numbers using the log as I do is by far the fastest solution.
1st digit of number from right → number % 10 = Math.floor((number / 1) % 10)
1234 % 10; // 4
Math.floor((1234 / 1) % 10); // 4
2nd digit of number from right → Math.floor((number / 10) % 10)
Math.floor((1234 / 10) % 10); // 3
3rd digit of number from right → Math.floor((number / 100) % 10)
Math.floor((1234 / 100) % 10); // 2
nth digit of number from right → Math.floor((number / 10^n-1) % 10)
function getDigit(number, n) {
return Math.floor((number / Math.pow(10, n - 1)) % 10);
}
number of digits in a number → Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1 Credit to: https://stackoverflow.com/a/28203456/6917157
function getDigitCount(number) {
return Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1;
}
nth digit of number from left or right
function getDigit(number, n, fromLeft) {
const location = fromLeft ? getDigitCount(number) + 1 - n : n;
return Math.floor((number / Math.pow(10, location - 1)) % 10);
}
Get rid of the trailing digits by dividing the number with 10 till the number is less than 100, in a loop. Then perform a modulo with 10 to get the second digit.
if (x > 9) {
while (x > 99) {
x = (x / 10) | 0; // Use bitwise '|' operator to force integer result.
}
secondDigit = x % 10;
}
else {
// Handle the cases where x has only one digit.
}
A "number" is one thing.
The representation of that number (e.g. the base-10 string "1234") is another thing.
If you want a particular digit in a decimal string ... then your best bet is to get it from a string :)
Q: You're aware that there are pitfalls with integer arithmetic in Javascript, correct?
Q: Why is it so important to not use a string? Is this a homework assignment? An interview question?
You know, I get that the question asks for how to do it without a number, but the title "JavaScript: Get the second digit from a number?" means a lot of people will find this answer when looking for a way to get a specific digit, period.
I'm not bashing the original question asker, I'm sure he/she had their reasons, but from a search practicality standpoint I think it's worth adding an answer here that does convert the number to a string and back because, if nothing else, it's a much more terse and easy to understand way of going about it.
let digit = Number((n).toString().split('').slice(1,1))
// e.g.
let digit = Number((1234).toString().split('').slice(1,1)) // outputs 2
Getting the digit without the string conversion is great, but when you're trying to write clear and concise code that other people and future you can look at really quick and fully understand, I think a quick string conversion one liner is a better way of doing it.
function getNthDigit(val, n){
//Remove all digits larger than nth
var modVal = val % Math.pow(10,n);
//Remove all digits less than nth
return Math.floor(modVal / Math.pow(10,n-1));
}
// tests
[
0,
1,
123,
123456789,
0.1,
0.001
].map(v =>
console.log([
getNthDigit(v, 1),
getNthDigit(v, 2),
getNthDigit(v, 3)
]
)
);
This is how I would do with recursion
function getDigits(n, arr=[]) {
arr.push(n % 10)
if (n < 10) {
return arr.reverse()
}
return getDigits(Math.floor(n/10),arr)
}
const arr = getDigits(myVar)
console.log(arr[2])
I don’t know why you need this logic, but following logic will get you the second number
<script type="text/javascript">
var myVal = 58445456;
var var1 = new Number(myVal.toPrecision(1));
var var2 = new Number(myVal.toPrecision(2));
var rem;
rem = var1 - var2;
var multi = 0.1;
var oldvalue;
while (rem > 10) {
oldvalue = rem;
rem = rem * multi;
rem = rem.toFixed();
}
alert(10-rem);
</script>
function getDigit(number, indexFromRight) {
var maxNumber = 9
for (var i = 0; i < indexFromRight - 2; i++) {
maxNumber = maxNumber * 10 + 9
}
if (number > maxNumber) {
number = number / Math.pow(10, indexFromRight - 1) | 0
return number % 10
} else
return 0
}
Just a simple idea to get back any charter from a number as a string or int:
const myVar = 1234;
String(myVar).charAt(1)
//"2"
parseInt(String(myVar).charAt(1))
//2
you can use this function
index = 0 will give you the first digit from the right (the ones)
index = 1 will give you the second digit from the right (the tens)
and so on
const getDigit = (num, index) => {
if(index === 0) {
return num % 10;
}
let result = undefined;
for(let i = 1; i <= index; i++) {
num -= num % 10;
num /= 10;
result = num % 10;
}
return result;
}
for Example:
getDigit(125, 0) // returns 5
gitDigit(125, 1) // returns 2
gitDigit(125, 2) // returns 1
gitDigit(125, 3) // returns 0
function left(num) {
let newarr = [];
let numstring = num.split('[a-z]').join();
//return numstring;
const regex = /[0-9]/g;
const found = numstring.match(regex);
// return found;
for(i=0; i<found.length; i++){
return found[i];
}
}
//}
console.log(left("TrAdE2W1n95!"))
function getNthDigit(n, number){
return ((number % Math.pow(10,n)) - (number % Math.pow(10,n-1))) / Math.pow(10,n-1);
}
Explanation (Number: 987654321, n: 5):
a = (number % Math.pow(10,n)) - Remove digits above => 54321
b = (number % Math.pow(10,n-1)) - Extract digits below => 4321
a - b => 50000
(a - b) / 10^(5-1) = (a - b) / 10000 => 5
var newVar = myVar;
while (newVar > 100) {
newVar /= 10;
}
if (newVar > 0 && newVar < 10) {
newVar = newVar;
}
else if (newVar >= 10 && newVar < 20) {
newVar -= 10;
}
else if (newVar >= 20 && newVar < 30) {
newVar -= 20;
}
else if (newVar >= 30 && newVar < 40) {
newVar -= 30;
}
else if (newVar >= 40 && newVar < 50) {
newVar -= 40;
}
else if (newVar >= 50 && newVar < 60) {
newVar -= 50;
}
else if (newVar >= 60 && newVar < 70) {
newVar -= 60;
}
else if (newVar >= 70 && newVar < 80) {
newVar -= 70;
}
else if (newVar >= 80 && newVar < 90) {
newVar -= 80;
}
else if (newVar >= 90 && newVar < 100) {
newVar -= 90;
}
else {
newVar = 0;
}
var secondDigit = Math.floor(newVar);
That's how I'd do it :)
And here's a JSFiddle showing it works :) http://jsfiddle.net/Cuytd/
This is also assuming that your original number is always greater than 9... If it's not always greater than 9 then I guess you wouldn't be asking this question ;)