This question already has an answer here:
Javascript Adding Two Decimal Places
(1 answer)
Closed 9 years ago.
I have a float,
var a = 324620.8
and I want it to look like this
a = 324620.80
This is my code so far,
var a_float = a;
var a_int = parseInt(a);
d = a_float - a_int;
if(d <= 0){
a = a_int+'.00';
}else{
if(d < 0 && d > 0.1){
a = a_int + d + '0';
}else{
a = a_float;
}
}
This would works for only one decimal digit.
I want it to work when I have 2 decimal digits.
.toFixed would not work in some browsers.
Answering the question in the title
How to find how many decimal digits in a float?
Compare position of '.' to length of float as a String.
var x = 1.2345,
x_str = x.toString(),
decimal_digits = x_str.length - x_str.lastIndexOf('.') - 1;
decimal_digits === x_str.length && (decimal_digits = 0); // case no decimal
decimal_digits; // 4
JSFIDDLE
Use toFixed("2");
var f = 1.3454545;
f.toFixed(2);
var decimal = 4.0;
var a = (decimal).toFixed(2);
console.log(a); // outputs 4.00
Related
This question already has answers here:
How to round to at most 2 decimal places, if necessary
(91 answers)
Closed 2 years ago.
So I'm having a problem of getting decimals. I can use them but when I do a calculation, that does not work. There's a lot of things to fix but is there any property that can help me?
let rank = prompt('Rank?', ''); // 2000
let x = prompt ('Value of x?', ''); // 90
let y = prompt ('Value of y?', ''); //1.6
var a = parseInt(rank); // 2000
var b = parseInt(x); // 90
var c = parseInt(y); // 1.6
var d = ((2000 - (500 * (3 - c)))/1000); // I get '1' instead of '1.3'
var e = d*b; // I get '90' instead of '117' (1.3*90)
var f = e*(y*y); // 334.0000004 (2*117) instead of 299.52 (2.56*117)
var g = b*(1-c); // 0 (90*(1-1)) instead of -54 (90*(1-1.6))
var h = a/90; // 22.2 is correct (2000/90)
var i = 2-c; // 0 because it rounds 1.6 to 2 (should be 0.4)
var j = h*i; // 0 and it should be 22.2*0.4
I just want to get rounded numbers in decimal part like 22.22222 becomes 22.2.
you want parseFloat, not parseInt
toFixed(1); // if you want rounded to 1 decimal place
This question already has answers here:
How to round to at most 2 decimal places, if necessary
(91 answers)
Closed 2 years ago.
My integer value is like below and
var amount= 5501;
var amount= 5500;
var amount= 5560;
var amount= 5563;
var amount= 5510;
i want split this integer like below .Have to add decimal point on middle. if last digit 0 not consider.
amount and should come "55.0.1"
amount and should come "55.0"
amount and should come "55.6"
amount and should come "55.6.3"
amount and should come "55.1"
i tried this ,
var variable1 = 5500;
function versionss(variable1){
var digits = (""+variable1).split("");
if(Number(digits[3] > 0)){
return Number(variable1/100) ; //
} else {
return digits[0]+digits[1]+'.'+digits[2];
}
}
Using Number.isInteger()
function versionss(amount) {
var divisor = Number(amount) > 999 ? 100 : 10;
var value = amount / divisor;
return Number.isInteger(value) ? value.toFixed(1) : value;
}
console.log(versionss(5501));
console.log(versionss(5500));
console.log(versionss(5560));
console.log(versionss(5563));
console.log(versionss(5510));
This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 6 years ago.
I have
var x = 100;
var y = 10;
var b = 10 /100 + 1;
var z = b*50
Expect z = 55. But I got z = 55.0000000001. I don't know why.
How do I fix it in Javascript.
Thanks
Use:
z = parseInt(z);
It will treat z as int.
Use toFixed for digits after the decimal point. Default is 0.
var x = 100;
var y = 10;
var b = 10 /100 + 1;
var z = b*50;
alert(z.toFixed(0));
alert(z.toFixed()); //both are same
For more reference : http://www.w3schools.com/jsref/jsref_tofixed.asp
This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 6 years ago.
I have created a function that takes a number in Imperial units entered into a div and converts that value to metric units in another div. Being relatively new to js, I am now realizing that a thousandths place comma separator does not come standard. I've tried to apply many of the solutions (many of them reg ex's) that I've found but none suit my needs or have worked. Simply put, I am just looking to have both divs outputted numbers have commas separating the thousandths place. Ultimately, these numbers are elevation values expressed in Feet and Meters. Any insight would be greatly appreciated... thanks!
Here is my code:
<body>
<div id="feet" onload="calculateMeter()">2120</div>
<div id="meter"></div>
<script>
var feet = document.getElementById('feet');
var meter = document.getElementById('meter');
function calculateMeter() {
if (feet.innerHTML > 0) {
meter.innerHTML = (feet.innerHTML * 0.3048).toFixed(1);
feet.toString();
feet = feet.innerHTML.replace(/(\d)(\d{3})\,/, "$1,$2.");
}
}
calculateMeter();
</script>
</body>
Here is a simple RegEx solution
function calculateMeter() {
if (feet.innerHTML > 0) {
var m = (feet.innerHTML * 0.3048).toFixed(2);
meter.innerHTML = m.replace(/\B(?=(\d\d\d)+\b)/g, ",");
}
}
It seems your problem is actually just setting the content the DOM element. Using the solution in How to print a number with commas as thousands separators in JavaScript for formatting numbers, all you need is:
function calculateMeter() {
if (feet.innerHTML > 0) {
meter.innerHTML = numberWithCommas*(feet.innerHTML * 0.3048).toFixed(1));
feet.innerHTML = numberWithCommas(feet.innerHTML);
}
}
My function:
function formatNumberWithCommasDec(d) {
d += "";
var c = d.split(".");
var f = c[1];
var a = c.length > 1 ? c[0] + '.' : '.', flag = false;
var g = f.split('').reverse(), y = 1, s = '';
for (var i = g.length - 1; i >= 0; i--) {
flag = false;
var e = g[i];
var h = (y === 3) ? s = s + e + ',' : s = s + e;
console.log(e);
if(y === 3){
y = 1;
flag = true;
} else {
y = y + 1;
}
}
if(flag){
s = s.substring(0, s.length - 1);
} else {
s = s;
}
return a + s;
}
Fiddle: https://jsfiddle.net/6f0tL0ec/1/
Update: found some problems, but everythings good now
Hi sorry for asking this if this is a stupid question.
I would like to ask how to securely divide a number in Javascript that it will always
output the result in a way that it will output pure whole numbers.
example:
10 / 2 ---> 5, 5 ( it would be 2 fives so it is whole number )
BUT
10 / 3 ---> 3, 3, 4 ( it would have two 3 and one 4 so that it would still result to 10 )
10/3 will give you 3.333333..., never four... if you want to check is a number will give you "whole numbers" as you say, use modulo (%).
Modulo finds the remainder of division of one number by another.
For example
10%5 = 0 because 10 divided by 5 is a "whole number"
10%3 = 1 because the closest 10/3 is 3... 3x3=9... 10-9=1
So in your code, if you want to know if a number divided by another number is whole, you need to do
if (number1%number2 == 0) { ... }
Read more about it here
EDIT :
I read your question again and I think this fiddle is what you want
var number1 = 10,
number2 = 3;
if (number1 / number2 == 0) {
alert('the numbers are whole');
} else {
var remainder = number1%number2;
var wholes = Math.floor(number1 / number2);
var output = '';
for (var i = 0; i < (wholes - 1); i++) {
output+= number2 + ', ';
}
output += (number2 + remainder);
alert(output);
}
Whatever your result is,just pass it through the parseInt function,For Eg:-
Suppose your answer is 4.3,
The whole number close to it will can be accounted using,
parseInt(4.3)
Which equals 4.
Another posibility: make the number a string and walk all the elements
var a = 11 / 4;
//turn it into a string and remove all non-numeric chars
a = a.toString().replace(/\D/g, '');
//split the string in seperate characters
a = a.split("");
var num = new Array();
//convert back to numbers
for (var i = 0; i < a.length; i++) {
num.push(parseFloat(a[i]));
}
alert(num);
On a sidenote, you'll have to do some kind of rounding, to prevent eternally repeating numbers, like 10/3.
Here is a fiddle
Look at this very simple example:
var x = 10;
var y = 3;
var result = x/y;
var rest = x%y;
for (var i=0; i<y; i++) {
var output;
if(i==y-1){
output = parseInt(result + rest);
}
else{
output = parseInt(result);
}
alert(output);
}
http://jsfiddle.net/guinatal/469Vv/4/