I have an issue,
I have a number that I wish to divide by 49 as shown in the code below:
// in Javascript:
let referenceNumber= 3487039819743582477;
let division = referenceNumber /49;
//I am using https://github.com/dcodeIO/long.js
//Now when I do the following with the Long.js library:
let longValue = Long.fromValue(division); //Long.js gave me 71164077953950662 as the result
//Now, in Kotlin:
val longValue = division.toDouble().toLong(); //Kotlin gave me 71164077953950664 as result
// As you can see, there is a difference of 2 between the two programming languages.
Which is the correct value here and How do I rectify this? I want both languages to give me exact value all the time after division and conversion to long
Thank you.
The problem is that you are doing toDouble(), which adds imprecision.
println(3487039819743582477 / 49) prints 71164077953950662.
If you want to know about Double and imprecision, check out https://floating-point-gui.de/.
Related
I have two long number that i represent those in JavaScript using BigInt ( because of the 53 bit integer length in JavaScipt instead of 64 bit). I found myself in the need to create out of those two long number an UUID / GUID in JavaScript.
In SO i was able to find the same question multiple times but always for different programming languages but not for JavaScript, example here:
Basically i am looking for something like the one in Java i.e. example here:
public UUID(long mostSigBits, long leastSigBits) {
this.mostSigBits = mostSigBits;
this.leastSigBits = leastSigBits;
}
and we can use it like:
UUID tempUUID1 = new UUID(55, 100);
results in :
00000000-0000-0037-0000-000000000064
The approach that i am thinking to take so far is convert the decimal to hex like that
BigInt("55").toString('16') // results to 37
BigInt("100").toString('16') // results to 64
and then pad the missing zeros. How such function can be implemented, I am looking for an example.
Preferably using the WebCryptoAPI (unfortunately node.js is not what i am looking for here), that can create and read/split such UUID / GUID to 2 separate BigInt's i.e. the "mostSigBits" and the "leastSigBits" values.
I would really appreciate if someone provides an example of such function / method . Thank you in advanced.
There's no need for a library, formatting these numbers is fairly straightforward substring'ing:
function formatAsUUID(mostSigBits, leastSigBits) {
let most = mostSigBits.toString("16").padStart(16, "0");
let least = leastSigBits.toString("16").padStart(16, "0");
return `${most.substring(0, 8)}-${most.substring(8, 12)}-${most.substring(12)}-${least.substring(0, 4)}-${least.substring(4)}`;
}
function formatAsUUID(mostSigBits, leastSigBits) {
let most = mostSigBits.toString("16").padStart(16, "0");
let least = leastSigBits.toString("16").padStart(16, "0");
return `${most.substring(0, 8)}-${most.substring(8, 12)}-${most.substring(12)}-${least.substring(0, 4)}-${least.substring(4)}`;
}
const expect = "00000000-0000-0037-0000-000000000064";
const result = formatAsUUID(BigInt("55"), BigInt("100"));
console.log(result, expect === result ? "OK" : "<== Error");
My code in Javascript involves manipulating several variables and displaying a few of them in counters on-screen. Because of the math I'm using, I'll end up with numbers such as 1842.47167... or something similar. I want to display the number as 1,843 (rounded and with the "thousands" comma added). Does anyone have a simple and easy way to do it? See below for code I've tried.
console.log(coins) //Output: 1842.4716796875
commaCoins = coins;
commaCoins = Math.round(coins);
commaCoins = coins.toLocaleString();
console.log(commaCoins) //Output: "1,842.472"
//Desired result: 1,843
Anyone have a better way to do this?
You'll need to work with strings to achieve that.
Something like:
const coins = 1842.4716796875;
const roundedCoins = Math.round(coins);
const dotFormat = roundedCoins / 1000
const commaFormat = dotFormat.toString().replace('.', ',');
console.log(commaFormat) // Output: 1,842
You can obviously do that in less step and use Math.ceil() if you need to round to the upper unit.
This is probably really simple, but for the life of me I can't work out how to do it. So here goes: I have a large form with lots of text boxes, which are all currency based and so need to be rounded off to 2 decimal places. The values of these textboxes are all generated dynamically by some JavaScript functions I wrote, and I can use .toFixed(2); to round them up/down to 2 decimal places. However, it gets tiring and repetitive to have to put this after working out each value of each textbox. How could I write a simple piece of JavaScript (can be jQuery) to target all the textboxes and round them ALL to 2 decimal places?
Thanks for any help :)
P.S Sorry for the lack of any code, but there isn't really any to show, as its all locked up in big functions. But here's what I'm essentially doing:
function workOutSomeVal() {
// lots of code to work out values and stuff
var finalValue = some mathematical equation to work out value;
var anotherValue = a different value;
$(".some-textbox").val((finalValue).toFixed(2));
$(".another-textbox").val((anotherValue).toFixed(2));
} // my question is, how could I get rid of .toFixed(2) and put in a generic statement somewhere to target all the textboxes?
You can have a function you call that does this:
function roundTextBoxes() {
$("input[type=text]").val(function() {
return (+this.value).toFixed(2);
});
}
...and then call that any time any of them changes. Live Example: http://jsbin.com/toyoc/1
It will probably mean that sometimes, a user looking at the page who does the mental arithmetic will find that it doesn't quite add up...
You can give a common class to all the textboxes which you want to be "roundable", and then select then using that class and apply your rounding logic to each of them.
// let's say all the roundable textboxes have the class "roundable"
$('.roundable').each(function() {
var value = // some mathematical equation to work out value
$(this).val((value).toFixed(2));
});
Another appoach:
Why don't you put value.toFixed(2) at the end of your calculation ?
var finalValue = function(){
// var value = some calculation
return value.toFixed();
}
Or - if you need the full value elsewhere, create a new function:
var finalValueView = function(){
finalValue().toFixed(2);
}
function workOutSomeVal() {
// ...
$(".some-textbox").val(finalValueView);
}
Use Math.round(num * 100) / 100
I need to sum several values in javascript. I've tried by using following code
var a = 2;
var b = 5;
c = a+b;
But, instead of calculating the values of a and b, the output (c) only combine those two values. So the output given is :
c = 25
I believe you guys can help me easily about this. Thx before. Regard Andha.
Make sure the values are numbers, otherwise they will concat instead of suming.
a = parseInt(a, 10); // a is now int
Your code is adding (concatenating) strings. Are you sure that the code you posted represents your problem? What you have written should work. Be sure in the real code you're not saying:
var a = '2'; // or something similar
Or if the values are parsed from somewhere, be sure to call parseInt(a, 10) on them before doing the addition, 10 being the radix.
Or as pointed out in the comments the Number function would probably suit your purposes.
The author has probably put "simplified" code so we can get an idea. Had same problem, while getting input values. JS interpreted it as string. Using "Number()" solved the problem:
var sum = Number(document.getElementById("b4_f2_"+i).value) + Number(document.getElementById("b4_f3_"+i).value) + Number(document.getElementById("b4_f4_"+i).value);
This works fine:
var a = 2;
var b = 5;
var c = a + b; // c is now 7
The code you show will not work the way you describe. It will result in 7.
However, when attempting to perform addition, if either or both numeric values are actually numeric strings, the other values will be cast to strings and they will be concatenated.
This is most likely to happen when attempting to read form values, reading cookies, or some other sort of HTTP header. To convert a string to a number, you need to use parseInt() [docs]. Read through the docs on it and be sure to pay attention to, and provide, the second parameter (radix) to ensure the casting from string to number uses the base you expect. (The lack of info on radix in other answers is the primary reason I went ahead and posted an answer even though others had already mentioned parseInt().)
Also, FYI, Another handy function to use when dealing with unknown values and hoping to perform mathematic operations is isNaN() [docs].
Use parseInt():
var a=2;
var b=5;
c=parseInt(a)+parseInt(b);
-Is important to apply Number() to every value. The ideal way is:
var sum = 0
sum = Number('93') + Number('7') //result 100
-instead of this way (careful with this)
var sum = 0
sum = Number('97' + '3') //result 937
-and careful with this (as variable is going to assign string type by default)
var sum = 0
sum = Number('97') + '3' //result "973"
You can simply convert string to a number by adding + before it. For somebody can be more readable.
Example:
const a = "2";
const b = "5";
const c = +a + +b
or const c = (+a) + (+b) may be more readable.
That will first convert the string to a Number.
I'm writing a small webpage that will enable students to answer questions and get feedback on their answers.
Part of this detection checks for common errors to give them guidance. Specifically I want to check if their answer is a power of ten out from the actual answer.
If the answer was 3.93E-6, this condition should activate if they type 3.93E2, 3.93E-9, 3.93 etc.
The obvious way to me to test this is to do something like this:
var correct = 3.93E-6;
var entry = 3.93E-2; //really comes from an input box.
if (!(entry / correct)%10) {
alert ("power of ten error");
}
However, this doesn't work as error/correct doesn't work for large/small numbers.
How can I fix this?
Live code at: http://bradshawenterprises.com/test.html
var num = 12.4123;
var numString = num.toExponential()
// numString = "1.24123e+1"
This normalizes the number, but you have to parse it manually. (Like on how accurate the result has to be…)
Here's one way to see if two numbers are off by approximately a power of ten:
var correct = 3.93E-6;
var entry = 3.93E-2;
var epsilon = .01;
var log10_ratio = Math.log(correct/entry)/Math.log(10);
if (Math.abs(Math.round(log10_ratio) - log10_ratio) < epsilon) {
alert ("power of ten error");
}
If they're required to enter the answer with the "E" notation, why not just check if all the stuff before the "E" is the same in both the student's answer, and the correct answer.
Of course you might also want to give them an idea of how many decimal places they should keep, otherwise 1.2E5 and 1.21E7 wouldn't trigger the "power of ten error"