How divide two numbers in java script - javascript

I am facing the issue in division of numbers in java script.
Example:
var x= 2500, var y = 100
alert(x/y)
is showing 25.
I need the answer in 25.00 format. What can I do?
When I divide 2536/100, it gives as expected.

You can try number.toFixed(x)
alert( (x/y).toFixed(2) )

You have to use the toPrecision() method: http://www.w3schools.com/jsref/jsref_toprecision.asp
It's a method defined in Number's prototype.
If you want to dynamically retrieve a float number with a specific precision (in your case 2), you can do de following:
var x = 2500;
var y = 100;
var res = x/y;
var desiredNumberOfDecimals = 2;
var floatRes = res.toPrecision(String(res).length + desiredNumberOfDecimals);

Try doing it this way:
alert((x/y).toFixed(2))

var x = 2500;
var y = 100;
alert( (x/y).toFixed(2) );

is it possible to enter x and y as a dollar amount? ie 25.00 and 1.00? if so then use the parseFloat method.
var x = 25.00
var y = 1.00
alert(parseFloat(x/y));

You need to take a look at number formatting and decimal precision etc.
Look here: http://www.mredkj.com/javascript/nfbasic2.html

Related

Unable to round simple javascript calculation

Currently this code outputs a string in two decimal places and I need it to be rounded to the closest integer. I had a play around with "math.round" but was unable to get it to work. Any assistance on this would be greatly appreciated!
function myFunction() {
var str = document.getElementById("blog-body").innerHTML;
var n = str.match(/(\w+)/g).length;
var x = n / 200;
var y = x.toFixed(2);
document.getElementById("result").innerHTML = y + ' Min |';
}
Thank you
Use toFixed(0)
Rounding to nearest integer: (123.123).toFixed(0) results in 123
(123.89).toFixed(0) results in 124
You can also use Math.round(123.3) results in 123 and Math.round(123.89) results in 124

Need to convert number to currency

Currently using below code for conversion of number to currency. The only issue is if I have 1000 it is giving 1000 instead I need 1k.
Current implementation 1000 - 1000
Need 1000 - 1k
Tried in lot many ways to get it done but unable to resolve.
var number = 12345678910;
var digits = 2;
var suffix = ["", "K.", "M.", "B."];
var nbDigits = parseInt(Math.log(number)/Math.LN10);
var power = nbDigits - nbDigits%3;
var tmp = number/ Math.pow(10, power);
var suffixIndex = Math.min(3, power/3);
var result = "$" + tmp.toFixed(digits) + " " + suffix[suffixIndex];
I got this solution from this link
Just simplify calculation of number of digits:
// From:
var nbDigits = parseInt(Math.log(number)/Math.LN10);
// To:
var nbDigits1 = Math.log10(number);
That'll give you the number of digits, without rounding errors. It does return $1.00 K. for 1000.
Hope this helps!

Create a float from two int numbers in JavaScript

How can I construct a float value from two whole values?
var amountBeforeComma = 5;
var amountAfterComma = 234;
var amount = ?? //amount == 5.234
There's the math way, using logarithms:
var amountBeforeComma = 5;
var amountAfterComma = 234;
var amount = amountBeforeComma +
amountAfterComma * Math.pow(10, -(Math.floor(Math.log10(amountAfterComma)) + 1));
console.log(amount);
Math.log10(amountAfterComma) gives us the common logarithm of amountAfterComma, then Math.floor(...) on that gives us the characteristic of it (2 in your example), which is (as the linked Wikipedia page puts it) "how many places the decimal point must be moved so that it is just to the right of the first significant digit". Then we add one to that and make it a negative (e.g., -3 in your example) and raise raise 10 to that power to get a value to multiply it by (0.001 in your example) to put it where it should go. Add the amountBeforeComma and we're done.
Or the string then parse way:
var amountBeforeComma = 5;
var amountAfterComma = 234;
var amount = parseFloat(amountBeforeComma + "." + amountAfterComma);
console.log(amount);
(Or use +(amountBeforeComma + "." + amountAfterComma) to convert with implicit coercion rather than explicit parsing.)
Since no one mentioned... There's the JavaScript way:
var num = +(amountBeforeComma + "." + amountAfterComma);
You can make it by casting numbers to strings and then parsing it as float.
var amount = parseFloat(amountBeforeComma + '.' + amountAfterComma);

Simple Javascript Math Function- addition/not working?

This is my function:
var ans=(X*X)/(Y+Z);
When I enter 10, 20, and 10 - respectively- the addition bit comes out as 2010 and not 30.
How can I fix this?
Make sure to convert your strings to numbers first:
var X = "10";
var Y = "20";
var Z = "10";
X = +X; // unary plus operator converts to a number
Y = Number(Y); // or use the Number function
Z = parseInt(Z, 10); // or parseInt
var ans=(X*X)/(Y+Z);

javascript, issue with number rounding

I knew javascript could have rounding issue with divisions, but not with multiplication. How do you solve those?
var p = $('input[name="productsUS"]').val().replace(",", ".");
var t = $('input[name="productsWorld"]').val().replace(",", ".");
if (p >= 0 && t >= 1) {
var r = p / t;
r = Math.round(r * 10000) / 10000;
var aff = (r * 100) + "%";
if p = 100 and t = 57674
r = 0.0017 (ok) and aff = 0.16999999999999998% (arg)
How could I obtain aff = 0.17?
("0.16999999999999998").tofixed(2) gives you 0.17.
var aff = (r * 100).toFixed(2) + "%";
Live DEMO
toFixed on MDN
If you want to aff to remain a Number instead of being converted to a String, you can use toFixed to work around the precision issues and then "cast" it back to a number using the unary + operator like so:
var n = 0.16999999999999998;
n = +n.toFixed(10); // 0.17
You probably want to use a higher precision than 2 decimal places to avoid rounding issues, I used 10 here.
That's a bug in JavaScript (although it also affects a few other languages, such as Python), due to the way it stores non-whole numbers being a bit buggy (binary!). The only way to work around it is to round it to two decimal places.

Categories