How subtraction of two float values in JavaScript? [duplicate] - javascript

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 4 years ago.
I have an issue with the subtraction of two values. when I set discount_amt value to 2.5 then total return me 0.5 but when discount_amt is set to 2.6 it return 0.3999999999999999 instead of 0.4 why?
var total = parseFloat('3').toFixed(1);
var discount_amt = parseFloat('2.6').toFixed(1);
total = total - discount_amt;
console.log(total);
var total = parseFloat('3').toFixed(1);
var discount_amt = parseFloat('2.6').toFixed(1);
total = total - discount_amt;
console.log(total);

This seems to fix it. You forget parsefloat() and tofixed()
total = 3;
discount_amt = 2.6;
console.log(parseFloat(total).toFixed(1) + ' ' + parseFloat(discount_amt).toFixed(1));
total = parseFloat(total).toFixed(1) - parseFloat(discount_amt).toFixed(1);
console.log(parseFloat(total).toFixed(1));
Explanation why floats are handled this way: answer or directly to the link that answer refers to link

Related

How to retain the first 2 numbers as is after the decimal point. Javascript [duplicate]

This question already has answers here:
Truncate (not round off) decimal numbers in javascript
(32 answers)
Closed 1 year ago.
I would like to format my numbers to always display 2 decimal places. lets say: I have a number => 21.268998 , the o/p I'm looking is to chop the rest of the decimal point and keep only the first 2 i.e:
21.26
however with the tofixed or toPrecision approach to always rounds to a certain decimal which is causing issues when a number is 99.999999, it rounds to 100.000 which is not right.
var num1 = "1";
document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2); // this is showing correctly
var num2 = "99.99999";
document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);// this is incorrect=> I want to show 99.99
any idea how to get the first numbers to show always without rounding them off to the next number.
Jsfiidle:
https://jsfiddle.net/8ohvyczg/1/
You can use slice method in javascript:
var num2 = 99.99999;
num2 = num2.slice(0, (num2.indexOf("."))+3);
document.getElementById('num2').innerHTML = num2;
Did u tried Math.trunc()?
var num = "99.99999";
var round=(Math.round(num * 100) / 100).toFixed(2)
var trunc=(Math.trunc(num * 100) / 100)
console.log(round);
console.log(trunc);
Here's an approach of a simple truncate, and not round off:
var number = 26.4363
var str = number.toString();
console.log(str.substring(0, str.indexOf(".")+3));
Many ways to do that. But you can write a custom function to do that. I use split and substring.
const num = "99.91999";
function parseNumber(num)
{
arr = num.split('.');
return arr[0] + '.' + arr[1].substring(0,2);
}
console.log(parseNumber(num))

Problem calculating the sum of arithmetic progression when using prompt() [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Javascript: "+" sign concatenates instead of giving sum of variables
(4 answers)
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I am trying this code to add a number starting from 1 to n using this mathematical equation:n = n(n+1) /2
var n = prompt("enter a number");
function adding(n) {
let N = n * (n + 1) / 2;
return N;
}
alert(adding(n));
but it's not working in prompt. It works like this:
function adding(n) {
let N = n * (n + 1) / 2;
return N;
}
console.log("answer", adding(100));

when taken 5 root of big number gives wrong answere in js [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 2 years ago.
When I take the 5 root of a big number, js gives me a wrong answer
var pow = 5;
var A = 133;
var B = 110;
var C = 84;
var D = 27;
var E;
E = Math.pow((Math.pow(A, pow) + Math.pow(B, pow) + Math.pow(C, pow) + Math.pow(D, pow)), 1/pow);
console.log(E)
This should give 144 but gives 144.00000000000003
5 root of 61917364224 = 144

Adding two integer JavaScript [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 6 years ago.
I am trying to add two numbers in JavaScript, but the result is inexact. This my example:
var x = 11.12, y = 11.07;
console.log(x + y); // the result is 22.189999999999998 but the real result is 22.19
Any solution for this?
This is what you need to do:
var x = 11.12, y = 11.07;
var result = (parseFloat(x) + parseFloat(y)).toFixed(2);
console.log( result );

Get random number based on probability [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I was wondering to get a random number with two decimal places based on probability for example:
40% to get number from 1-10
20% to get number from 11-20
30% to get number from 21-30
10% to get number from 31-35
function Prob(){
var rnd = Math.random(),
rnd2 = Math.random();
if(rnd<0.4) return (1 + Math.floor(1000 * rnd2)/100);
else if(rnd<0.6) return (11 + Math.floor(1000 * rnd2)/100);
else if(rnd<0.9) return (21 + Math.floor(1000 * rnd2)/100);
else return (31 + Math.floor(500 * rnd2)/100);
}
You need two random numbers, so I calculate them at the start. I then use the if-else loops to cycle through your 40%, 20%, 30% and 10% (adding them up as I go). Note: Math.random returns a number between 0 and 1. Then for each catagory I use the SECOND random number to get in the range you have said - floor it to make sure it is an integer and add the starting number of each range. Note: the range of your last one is just 5.
I should explain, you must use two random numbers, otherwise the range of the second number would be dependent on which category you are in.
I have to do the 1000 * rnd2 in the floor and then divide by 100 outside to get the 2 decimal place you ask for.
Rewind's solution is great and specifically tailored to OP's quesiton. A more re-usable solution might be:
function getNumber(probabilities){
var rnd = Math.random();
var total = 0;
var hit;
for(var i = 0; i < probabilities.length; i++){
if(rnd > total && rnd < total + probabilities[i][0]){
hit = probabilities[i]
}
total += probabilities[i][0];
}
return Number((hit[1] + (Math.random() * (hit[2] - hit[1]))).toFixed(2));
}
var number = getNumber(
[
//chance, min, max
[0.4, 1, 10],
[0.2,11,20],
[0.3,21,30],
[0.1,31,35]
]
);
console.log(number);
The function will take an array with the probabilities, for each probability you specify the chance, the minimum value for that chance, the maximum value for that chance. It will return a number with two decimals.
https://jsfiddle.net/x237w5gv/
I guess this
var get1120 = _ => ~~(Math.random()*10)+11,
get2130 = _ => ~~(Math.random()*10)+21,
get3135 = _ => ~~(Math.random()*5)+31,
a = [get3135,get1120,get1120,get2130,get2130,get2130],
fun;
result = (fun = a[~~(Math.random()*10)]) ? fun() : ~~(Math.random()*10)+1;
console.log(result);
might do it;

Categories

Resources