Number decimal is displaying wrong [duplicate] - javascript

This question already has answers here:
javascript - how to prevent toFixed from rounding off decimal numbers
(7 answers)
Closed 5 years ago.
I am defining my numberfield and then I amgetting some value like this
val = 3.555678
I am using decimalPrecision : 3 in my number field so The value is displaying is 3.556
I want my value should be display 3.555 so for that I am using
val = val.toFixed(3);
val is coming in consol 3.555
then numberfield.setValue(val);
But in UI it is still comming 3.556
Why it is coming this.

I you want to display 3.555 you can do it in the following way
let val = 3.555678
let decimalPrecision = 3;
let roundedval = val.toFixed(3);
if(roundedval > val){
val = roundedval - Math.pow(10, -1*decimalPrecision);
}
console.log(val);

You can use:
var val=3.555678;
val = Math.floor (val*1000)/1000;
console.log(val);

Related

Why my function returns int without sum of 1, or it sums random number [duplicate]

This question already has answers here:
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 3 months ago.
I'm trying to convert Steam ID 32bit to Steam ID 64bit.
My javascript function is not working right but same function in python works fine. Python function is copied from How can I get a steamid 64 from a steamID in python
function steamidTo64(steamid) {
let steam64id = 76561197960265728; // Valve's magic constant
let id_split = steamid.split(":");
steam64id += parseInt(id_split[2]) * 2;
if (id_split[1] == "1") {
steam64id += 1;
}
return steam64id;
}
Using input of STEAM_1:1:191000236 function should return 76561198342266201, but instead it returns 76561198342266200
Using input of STEAM_1:1:3645504 function should return 76561197967556737, but it returns 76561197967556740
Using input of STEAM_0:0:570629725 function should return 76561199101525178, but it returns 76561199101525180
You will need to use BigInt since 76561197960265728 is greater than 9007199254740992 (1 digit longer), and so arithmetic operations on this number are inaccurate and can lead to incorrect results.
function steamidTo64(steamid) {
let steam64id = 76561197960265728n;
const id_split = steamid.split(":");
steam64id += BigInt(id_split[2]) * 2n;
if (id_split[1] === "1") steam64id += 1n;
return steam64id;
}
// Result is BigInt
console.log(steamidTo64("STEAM_1:1:191000236").toString());

Average calculator finding strange and incorrect numbers [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 3 years ago.
I am trying to make an average calculator. This is my code for it:
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i++;
}
}
var average = total / data.length;
document.write(average);
It seems to take input well, however something goes wrong when it comes to calculation. It says that the average of 6 and 6 is 33, 2 and 2 is 11, and 12 and 6 is 306. These are obviously wrong. Thank you in advance for your help.
You need to take a number, not a string value from the prompt.
The easiest was is to take an unary plus + for converting a number as string to a number
data.push(+newdata);
// ^
Your first example shows, with '6' plus '6', you get '66', instead of 12. The later divsion converts the value to a number, but you get a wrong result with it.
It is taking the input as string. Convert the input to floats before putting them in the array. I think its performing string additions like 6+6=66 and then 66/2 = 33. Similar is the case of 2 and 2.

Javascript wrong math [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 6 years ago.
I'm not sure what's wrong.
There are two variables, cena and uhrada. cena = 10 and uhrada = 279.8. I want to add them but I am getting 279.810 instead of 289.8.
Thanks for any help!
function priplatok(vstup1, vstup2) {
var chid = vstup1;
var cena = vstup2;
var uhrada = document.getElementById('uhr').value;
if (document.getElementById(chid).checked) {
var pridatu = uhrada + cena;
alert(pridatu);
}
}
The reason is that the values you take from the HTML input elements are always strings, even when they look like numbers. You have to first convert them, for instance with parseInt(...) or parseFloat():
var pridatu = parseFloat(uhrada) + parseFloat(cena);
A shorter way is to force conversion with a +:
var pridatu = +uhrada + +cena;
Although this is concise, you should probably first check if the input really is numeric. I refer to a popular question "Validate decimal numbers in JavaScript - IsNumeric()".
You get a string from document.getElementById('uhr').value.
If you want to do math, you need to cast the value either with parseInt(string, 10) or with parseFloat(string) to a number, implicit with a unary plus.
Your code:
function priplatok(vstup1, vstup2) {
var chid = vstup1;
var cena = vstup2;
var uhrada = +document.getElementById('uhr').value; // use implicit cast to number
if (document.getElementById(chid).checked) {
var pridatu = uhrada + cena;
alert(pridatu);
}
}
Thats because the values are strings and not numbers.
You have to make them numbers first and then calculate:
var pridatu = parseInt(uhrada) + parseInt(cena);

Javascript sum of values in table [duplicate]

This question already has answers here:
How to format a float in javascript?
(14 answers)
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 9 years ago.
I've succesfully used this code to calculate sums in a table:
var $overall = 0;
$("tr.sum").each(function()
{
var $qnt = $(this).find("td").eq(0);
var $price = $(this).find("td").eq(1);
console.log($qnt+" | "+$price);
var sum = parseFloat($price.text()) * parseFloat($qnt.text());
$(this).find("td").eq(2).text(sum);
$overall+= sum;
});
$("#total").text($overall); });
I changed one line to avoid rounding errors:
var sum = parseFloat((parseFloat($price.text().replace(',', '.')) * parseFloat($qnt.text().replace(',', '.'))).toFixed(2));
It works fine. But I can't solve the problem to round the total sum to two decimal places.
$("#total").text($overall);
I tried toFixed(2). But this results in a string and not a number.
Any help would be appreciated!
Thanks, Mike
after doing all calculation make it like this
$overall.toFixed(2);

How to generate random numbers in Javascript [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Generating random numbers in Javascript
Hi..
I want to generate random numbers (integers) in javascript within a specified range. ie. 101-999. How can I do that. Does Math.random() function supports range parameters ?
Just scale the result:
function randomInRange(from, to) {
var r = Math.random();
return Math.floor(r * (to - from) + from);
}
The function below takes a min and max value (your range).
function randomXToY(minVal,maxVal)
{
var randVal = minVal+(Math.random()*(maxVal-minVal));
return Math.round(randVal);
}
Use:
var random = randomXToY(101, 999);
Hope this helps.
Math.floor(Math.random()*898)+101

Categories

Resources