I'm facing a problem to get the digit of a number after decimal point. I need the digit to do if else statement.
Here is an example:
31.30 = 31.30
31.31 = 31.30
31.32 = 31.30
31.33 = 31.35
31.34 = 31.35
31.35 = 31.35
31.36 = 31.35
31.37 = 31.35
31.38 = 31.40
31.39 = 31.30
So, I need to get the second digit after decimal point. Then, i can use the digit to do if else statement. This rounding issue is happening in Malaysia.
Something like this might work for doing the rounding to the nearest 5 cents, although then you may need to format the output to have the proper number of digits past the decimal point:
var origVal = 31.34;
var roundedVal = Math.round(origVal*20)/20;
Which would give you 31.35, i.e., rounded to the nearest nickel.
This seems a little more direct than getting the digit and doing an if/else.
Simply try Math.round(x*100%10)
for a part of your question
you can round javascript to specific precision by
Link :Number rounding in JavaScript
var original=28.453
1) //round "original" to two decimals
var result=Math.round(original*100)/100 //returns 28.45
2) // round "original" to 1 decimal
var result=Math.round(original*10)/10 //returns 28.5
3) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000 //returns 8.111
from How can I round down a number in Javascript?
Round towards negative infinity - Math.floor()
+3.5 => +3.0
-3.5 => -4.0
Round towards zero - usually called Truncate(), but not supported by JavaScript - can be emulated by using Math.ceil() for negative numbers and Math.floor() for positive numbers.
+3.5 => +3.0 using Math.floor()
-3.5 => -3.0 using Math.ceil()
Related
I have one php function and having
phpans = round(53.955,2)
and javascript function
var num = 53.955;
var jsans = num.toFixed(2);
console.log(jsans);
both jsans and phpans is giving different $phpans = 53.96 ans jsans = 53.95 . I can not understand why this is happening ..
Thanks is Advance
Because computers can't represent floating numbers properly. It's probably 53.95400000000009 or something like that. The way to deal with this is multiply by 100, round, then divide by 100 so the computer is only dealing with whole numbers.
var start = 53.955,
res1,
res2;
res1 = start.toFixed(2);
res2 = (start * 100).toFixed(0) / 100;
console.log(res1, res2);
//Outputs
"53.95"
53.96
JAvascript toFixed:
The toFixed() method converts a number into a string, keeping a specified number of decimals.
php round:
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
Conclusion tofixed not working like php round. precision Specifies the number of decimal digits to round to.
Javascript function :
function round_up (val, precision) {
power = Math.pow (10, precision);
poweredVal = Math.ceil (val * power);
result = poweredVal / power;
return result;
}
toFixed() function responding differently for float values.
For Example:
var a = 2.555;
var b = 5.555;
console.log(a.toFixed(2)); /* output is 2.56 */
console.log(b.toFixed(2)); /* output is 5.55 */
For 2.555/3.555 results are (2.56/3.56)
and
For other values(not sure for all values) it is showing #.55 (# refers to any number)
I am confused can any one help me out.
Thanks in advance.
Javascript uses a binary floating point representation for numbers (IEEE754).
Using this representation the only numbers that can be represented exactly are in the form n/2m where both n and m are integers.
Any number that is not a rational where the denominator is an integral power of two is impossible to represent exactly because in binary it is a periodic number (it has infinite binary digits after the point).
The number 0.5 (i.e. 1/2) is fine, (in binary is just 0.1₂) but for example 0.55 (i.e. 11/20) cannot be represented exactly (in binary it's 0.100011001100110011₂… i.e. 0.10(0011)₂ with the last part 0011₂ repeating infinite times).
If you need to do any computation in which the result depends on exact decimal numbers you need to use an exact decimal representation. A simple solution if the number of decimals is fixed (e.g. 3) is to keep all values as integers by multiplying them by 1000...
2.555 --> 2555
5.555 --> 5555
3.7 --> 3700
and adjusting your computation when doing multiplications and divisions accordingly (e.g. after multiplying two numbers you need to divide the result by 1000).
The IEEE754 double-precision format is accurate with integers up to 9,007,199,254,740,992 and this is often enough for prices/values (where the rounding is most often an issue).
Try this Demo Here
function roundToTwo(num) {
alert(+(Math.round(num + "e+2") + "e-2"));
}
roundToTwo(2.555);
roundToTwo(5.555);
toFixed() method depending on Browser rounds down or retain.
Here is the solution for this problem, check for "5" at the end
var num = 5.555;
var temp = num.toString();
if(temp .charAt(temp .length-1)==="5"){
temp = temp .slice(0,temp .length-1) + '6';
}
num = Number(temp);
Final = num.toFixed(2);
Or reusable function would be like
function toFixedCustom(num,upto){
var temp = num.toString();
if(temp .charAt(temp .length-1)==="5"){
temp = temp .slice(0,temp .length-1) + '6';
}
num = Number(temp);
Final = num.toFixed(upto);
return Final;
}
var a = 2.555;
var b = 5.555;
console.log(toFixedCustom(a,2));
console.log(toFixedCustom(b,2));
I've following formula in Wolfram:
log base 10 of (10^-18x)
WolframLink (with x example)
First of all Log Function:
function getLog(y) {
return Math.log(y)/Math.log(10);
}
Now I'm trying to get my value:
var x = Math.pow(10,33);
var faktor = getLog(Math.pow(10,-(18*x)));
console.log(faktor);
console gives -Infinity
What is wrong about my code? Thanks for help.
Your computations are causing floating point underflow. A floating point number is roughly represented as 0.<mantissa> × 2<exponent>, so that the distribution of log(|x|) for representable values x is uniformly dense. Both the mantissa and exponent have a certain number of bits allocated for them. The exponent of the representation can only become so small, and if you try to make it smaller than the minimum, the representation is forced to round to 0.
You can instead perform your computations in logspace using these identities. A few of these are listed here.
log(x × y) = log(x) + log(y)
log(x / y) = log(x) - log(y)
log(xy) = y × log(x)
You are overflowing the maximum integer allowed in JavaScript by quite a bit.
Max int in JS
Wolfram proof because why not
You are going to need a big number extension of JavaScript, which SO has many posts about. See here for what appears to be unlimited integer math
More posts like this can be chased starting here
Code
Values in practice:
var x = Math.pow(10,33); // x = 1.0000000000000001e+33
var exponent = -18*x; // exponent = -1.8000000000000002e+34
var deci = Math.pow(10, exponent); // deci = 0
var logged = Math.log(deci); // logged = NaN (-Infinity)
var result = logged/Math.log(10); // result = NaN (-Infinity)
The problem is that floating point values can have decimal exponents in the range -308 to +308 (approximately, it's really all in binary), and your exponent is approximately 18,000,000,000,000,002,000,000,000,000,000,000.
Maths
Maths gives us log(xy) = y.log(x). And that logb(b) = 1. Thus,
log10(10-18x) = -18x.log(10) = -18x.
So the maths lesson is that "logging X (base b)" and "raising b to the power of X" are inverse operations.
This question already has answers here:
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 9 years ago.
alert(5.30/0.1);
This gives 52.99999999999999 but should be 53. Can anybody tell how and why?
I want to find that a number is divisible by a given number. Note that one of the number may be a float.
For the same reason that
0.1 * 0.2 //0.020000000000000004
Some decimal numbers can't be represented in IEEE 754, the mathematical representation used by JavaScript. If you want to perform arithmetic with these numbers in your question, it would be better to multiply them until they are whole numbers first, and then divide them.
Scale the numbers to become whole. Then modulus the result.
alert((5.30*10) % (0.1*10));
Now that you have read the article i commented, you should know the root of your problem.
You can partially work around that by scaling you floats...
Then just write a function which:
If its a float
Scale the Numbers
return a boolean representation of the divisibility of the number
function isDivisable(n, d) {
var ndI = 1 + "".indexOf.call(n, "."); //Index of the Number's Dot
var ddI = 1 + "".indexOf.call(d, "."); // Index of the Divisors Dot
if (ndI || ddI) { // IF its a float
var l = Math.max(("" + n).length - ndI, ("" + d).length - ddI); //Longest Decimal Part
var tmpN = (n * Math.pow(10, l)); //scale the float
var tmpD = (d * Math.pow(10, l));
return !~((tmpN % tmpD) - 1); //Substract one of the modulo result, apply a bitwise NOT and cast a boolean.
}
return !~((n % d) - 1); // If it isnt a decimal, return the result
}
console.log(isDivisable(5.30, 0.1));//true
Heres a JSBin
However...
As Integers are stored with 64bit precision, the maximum precision lies about (2^53),
and you will soon exceed the maximum precision when scaling larger numbers.
So it might be a good idea to get some sort of BigInteger Library for javascript
if you want to test floats for divisibility
To find if a number x is divisible by a number y you have to do x % y (modulo). If the result is 0, it is perfectly divisible, any other isn't.
You can get it by following:
var num = (5.30/0.1);
alert(num.toFixed(2));
this will give you 53.00.
While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of
Name : Value
Name2 : Value2
etc.
The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?
If you need to round to a certain number of digits use the following function
function roundNumber(number, digits) {
var multiple = Math.pow(10, digits);
var rndedNum = Math.round(number * multiple) / multiple;
return rndedNum;
}
You hav to convert your input into a number and then round them:
function toInteger(number){
return Math.round( // round to nearest integer
Number(number) // type cast your input
);
};
Or as a one liner:
function toInt(n){ return Math.round(Number(n)); };
Testing with different values:
toInteger(2.5); // 3
toInteger(1000); // 1000
toInteger("12345.12345"); // 12345
toInteger("2.20011E+17"); // 220011000000000000
According to the ECMAScript specification, numbers in JavaScript are represented only by the double-precision 64-bit format IEEE 754. Hence there is not really an integer type in JavaScript.
Regarding the rounding of these numbers, there are a number of ways you can achieve this. The Math object gives us three rounding methods wich we can use:
The Math.round() is most commonly used, it returns the value rounded to the nearest integer. Then there is the Math.floor() wich returns the largest integer less than or equal to a number. Lastly we have the Math.ceil() function that returns the smallest integer greater than or equal to a number.
There is also the toFixed() that returns a string representing the number using fixed-point notation.
Ps.: There is no 2nd argument in the Math.round() method. The toFixed() is not IE specific, its within the ECMAScript specification aswell
Here is a way to be able to use Math.round() with a second argument (number of decimals for rounding):
// 'improve' Math.round() to support a second argument
var _round = Math.round;
Math.round = function(number, decimals /* optional, default 0 */)
{
if (arguments.length == 1)
return _round(number);
var multiplier = Math.pow(10, decimals);
return _round(number * multiplier) / multiplier;
}
// examples
Math.round('123.4567', 2); // => 123.46
Math.round('123.4567'); // => 123
You can also use toFixed(x) or toPrecision(x) where x is the number of digits.
Both these methods are supported in all major browsers
You can use Math.round() for rounding numbers to the nearest integer.
Math.round(532.24) => 532
Also, you can use parseInt() and parseFloat() to cast a variable to a certain type, in this case integer and floating point.
A very good approximation for rounding:
function Rounding (number, precision){
var newNumber;
var sNumber = number.toString();
var increase = precision + sNumber.length - sNumber.indexOf('.') + 1;
if (number < 0)
newNumber = (number - 5 * Math.pow(10,-increase));
else
newNumber = (number + 5 * Math.pow(10,-increase));
var multiple = Math.pow(10,precision);
return Math.round(newNumber * multiple)/multiple;
}
Only in some cases when the length of the decimal part of the number is very long will it be incorrect.
Math.floor(19.5) = 19 should also work.