How can I have the value round up in javascript? - javascript

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

Related

ToFixed function on ActionScript/Javascript

First time in stackoverflow, but I really need help on reconstructing this string.
So basically its in Actionscript and I'd need to reconstruct the Millions-string to output as 1.23M, AKA contain millions with thousands beside it as currently it only shows 1M. I have heard that toFixed would do the trick, but I can't seem to get it to work as my favour.
Any examples would help, thank you!
public static function balanceToString(value:int):String
{
var suffix:String = "";
var resultValue:int = value;
if (value >= 1000000)
{
resultValue = Math.floor(resultValue / 1000000);
resultValue.toFixed(4);
suffix = "M";
}
else if (value >= 100000)
{
resultValue = Math.floor(resultValue / 1000);
suffix = "K";
}
return "" + resultValue.toString() + suffix;
}
You are converting your number to int in the signature.
Try using a Number instead.
public static function balanceToString(value:Number):String
{
var suffix:String = "";
var resultValue:Number = value;
if (value >= 1000000)
{
resultValue = Math.floor(resultValue / 1000000);
resultValue.toFixed(4);
suffix = "M";
}
else if (value >= 100000)
{
resultValue = Math.floor(resultValue / 1000);
suffix = "K";
}
return "" + resultValue.toString() + suffix;
}
Something like this, I guess.
Implementation:
public static function balanceToString(value:int):String
{
var suffix:String = "";
var divisor:Number = 1;
var precision:Number = 0;
if (value >= 100000)
{
// This will display 123456 as 0.12M as well.
divisor = 1000000;
precision = 2;
suffix = "M";
}
else if (value >= 500)
{
// This will display 543 as 0.5K.
divisor = 1000;
precision = 1;
suffix = "K";
}
// This allows you to control, how many digits to display after
// the dot . separator with regard to how big the actual number is.
precision = Math.round(Math.log(divisor / value) / Math.LN10) + precision;
precision = Math.min(2, Math.max(0, precision));
// This is the proper use of .toFixed(...) method.
return (value / divisor).toFixed(precision) + suffix;
}
Usage:
trace(balanceToString(12)); // 12
trace(balanceToString(123)); // 123
trace(balanceToString(543)); // 0.5K
trace(balanceToString(567)); // 0.6K
trace(balanceToString(1234)); // 1.2K
trace(balanceToString(12345)); // 12K
trace(balanceToString(123456)); // 0.12M
trace(balanceToString(1234567)); // 1.23M
trace(balanceToString(12345678)); // 12.3M
trace(balanceToString(123456789)); // 123M

Sorting an integer without using string methods and without using arrays

can anyone come with an idea of how to sort an integer without using an array, and without using string methods as well as sort() method?
for example
input: 642531
output: 123456
I started by writing 2 simple functions - one which checks the length of the number, the other one splits the integer at some point and switches between 2 desired numbers. Below are the 2 functions.
I got stuck with the rest of the solution...
function switchDigits(num, i) { // for input: num=642531, i = 4 returns 624135
let temp = num;
let rest = 0;
for (let j = 0; j < i - 1; j++) {
rest = rest * 10;
rest = rest + temp % 10;
temp = (temp - temp % 10) / 10;
}
let a = temp % 10;
temp = (temp - a) / 10;
let b = temp % 10;
temp = (temp - b) / 10;
temp = Math.pow(10, i - 2) * temp;
temp = temp + 10 * a + b;
temp = Math.pow(10, i - 1) * temp;
temp = temp + rest;
return temp;
}
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
let num = 642534;
let i = checkHowManyDigits(num);
console.log(switchDigits(num));
It actually complicated requirement and so does this answer. It's pure logic and as it is it's a question from a test you should try understanding the logic on your own as a homework.
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
function sortDigit(numOriginal) {
let i = checkHowManyDigits(numOriginal);
let minCount = 0;
let min = 10;
let num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d < min) {
min = d;
minCount = 0;
} else if (d === min) {
minCount++;
}
}
let result = 0;
while (minCount >= 0) {
result += min * Math.pow(10, i - minCount - 1);
minCount--;
}
let newNum = 0;
num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d !== min) {
newNum = newNum * 10 + d;
}
}
if (newNum == 0) return result;
else return result += sortDigit(newNum);
}
console.log(sortDigit(642531));
You could have a look to greater and smaller pairs, like
64
46
The delta is 18, which gets an idea if you compare other pairs, like
71
17
where the delta is 54. Basically any difference of two digits is a multiple of 9.
This in mind, you get a function for taking a single digit out of a number and a single loop who is sorting the digits by using the calculated delta and subtract the value, adjusted by the place.
function sort(number) {
const
getDigit = e => Math.floor(number / 10 ** e) % 10,
l = Math.ceil(Math.log10(number)) - 1;
let e = l;
while (e--) {
const
left = getDigit(e + 1),
right = getDigit(e);
if (left <= right) continue;
number += (right - left) * 9 * 10 ** e;
e = l;
}
return number;
}
console.log(sort(17)); // 17
console.log(sort(71)); // 17
console.log(sort(642531)); // 123456
console.log(sort(987123654)); // 123456789
So eventually I found the best solution.
*This solution is based on a Java solution I found in StackOverFlow forums.
let store = 0;
function getReducedNumbr(number, digit) {
console.log("Remove " + digit + " from " + number);
let newNumber = 0;
let repeateFlag = false;
while (number>0) {
let t = number % 10;
if (t !== digit) {
newNumber = (newNumber * 10) + t;
} else if (t == digit) {
if (repeateFlag) {
console.log(("Repeated min digit " + t + " found. Store is : " + store));
store = (store * 10) + t;
console.log("Repeated min digit " + t + " added to store. Updated store is : " + store);
} else {
repeateFlag = true;
}
}
number = Math.floor(number / 10);
}
console.log("Reduced number is : " + newNumber);
return newNumber;}
function sortNum(num) {
let number = num;
let original = number;
let digit;
while (number > 0) {
digit = number % 10;
console.log("Last digit is : " + digit + " of number : " + number);
temp = Math.floor(number/10);
while (temp > 0) {
console.log("subchunk is " + temp);
t = temp % 10;
if (t < digit) {
digit = t;
}
temp = Math.floor(temp/10);
}
console.log("Smallest digit in " + number + " is " + digit);
store = (store * 10) + digit;
console.log("store is : " + store);
number = getReducedNumbr(number, digit);
}
console.log(("Ascending order of " + original + " is " + store));
return store;
}
console.log(sortNum(4214173));
you can see how it works here https://jsfiddle.net/9dpm14fL/1/

Convert HEX to Signed INT Javascript [duplicate]

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

parseInt value from input and use as a check for the sum of last value with Javascript

Trying to track the numbers in an input value and use these as a checkdigit for the last number. Basically, grab the first nine digits of the input, run some simple math and then add those numbers together. Take that total, divide by two then use the remainder as the check digit.
Thus far unsuccessful so if anyone has a good idea of where I am going wrong would gladly appreciate it. I put a fiddle up here: Das Fiddle
window.onkeyup = keyup;
var inputTextValue;
function keyup(e) {
inputTextValue = e.target.value;
$('#numberValue').text(inputTextValue);
// must be 10 characters long
if (inputTextValue.length !== 10) {
return false;
}
// run the checksum
var valid = false;
try {
var sum = (parseInt(inputTextValue[0], 10) * 2) +
(parseInt(inputTextValue[1], 10) * 3) +
(parseInt(inputTextValue[2], 10) * 4) +
(parseInt(inputTextValue[3], 10) * 2) +
(parseInt(inputTextValue[4], 10) * 3) +
(parseInt(inputTextValue[5], 10) * 4) +
(parseInt(inputTextValue[6], 10) * 2) +
(parseInt(inputTextValue[7], 10) * 3) +
(parseInt(inputTextValue[8], 10) * 4);
var checkNumber = 0;
if ((sum % 10) > 0) {
checkNumber = (sum % 10).toFixed(-1);
}
if (inputTextValue[9] === ("" + checkNumber)) {
valid = true;
alert(checkNumber)
}
} catch (e) {
valid = false;
}
return valid;
}
You should be using :
checkNumber = (sum % 10).toFixed(0);
toFixed(-1) will return 0.
Fiddle here

jquery convert results of decimal into fractions

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

Categories