Javascript decimal number comparison - javascript

I have two decimal numbers which only slightly differ at the last two decimal places
eg. num1 = 1.12345 and num2 = 1.1234567
but doing a num1 === num2 check fails.
What would be the best way in javascript to make the comparison return true if there are only few extra decimal places in num2 compared to num1?
I know that num2 could be rounded by few decimal problems but therein arises the problem because I don't know in advance how many decimal places would be truncated in num1.

There are two possible ways of doing this (that I am aware of). The first would be to use toFixed, to round your numbers. The second would be to present some precision factor, in order to define "slightly" (let's say slightly means "a difference less than 0.0001"). The functions that implement this are below
// a, b - the numbers you wish to compare, digits - the number of digits to round to
function compareUpTo(a, b, digits){
a.toFixed(digits) === b.toFixed(digits) // first we round the numbers, then we compare them
}
// a, b - the numbers you wish to compare, precision- the amount to which the numbers are allowed to be different (let's say 0.01 for up to two digits)
function compareUpTo2(a, b, precision){
Math.abs(a-b) < precision // we make the difference and check whether or not the difference is smaller than our desired precision (we use Math.abs to turn a negative difference into a positive one)
}

Your definition of === is not what === means, but I think I get what you are trying to do.
First, figure out which number is the shortest.
Then, only compare the numbers by the amount of decimals in the shorter number.
I'm sure there is a cleaner way to do this, but I've drawn it out step-by-step to show the progression and to help make sense of the process.
function compare(x, y){
// Convert both numbers to strings:
var str1 = x.toString();
var str2 = y.toString();
// Get the shortest string
var shortest = str1.length >= str2.length ? str2 : str1;
console.log("Shorter number is: " + shortest); // Just for testing
// Get number of decimals in shorter string
var dec = shortest.indexOf(".");
var numDecimals = shortest.length - dec - 1;
// Only compare up to the least amount of decimals
console.log(x + " and " + y + " equal? " + (str1.substr(0, numDecimals + dec + 1) === str2.substr(0, numDecimals + dec + 1)));
}
compare(1.12345, 1.1234567);
compare(1.22345, 1.1234567);
compare(-101.22345, -101.1234567);
compare(-101.12345, -101.1234567);

You can use toString and compare strings. This will solve the problem of not knowing in advance the number of digits.
num1 = 1.12345 ;
num2 = 1.1234567 ;
str1 = num1.toString();
str2= num2.toString();
leng1 =str1.length;
leng2=str2.length;
minLength = Math.min(leng1 ,leng2);//ignore extra decimals
str1 =str1.slice(0,minLength);
str2 =str2.slice(0,minLength);
console.log(str1 ===str2); //true

The way I would do this is to find the length of the "shorter" number, then truncate the "longer" number with this code from MDN:
function truncate(number, precision) {
var factor = Math.pow(10, precision);
// *shouldn't* introduce rounding errors
return Math.floor(number * factor) / factor;
}
Where precision is the length of the shorter number. Which, you could get like this:
let num1 = 1.12345,
num2 = 1.1234567;
// gets everything after the . as a string
let str1 = String.prototype.split.call(num1,'.')[1],
str2 = String.prototype.split.call(num2,'.')[1];
let precision = Math.min(str1.length, str2.length);
Then, call the above function on both numbers and do your comparison.
if(truncate(num1,precision) == truncate(num2,precision) //do stuff
I modified the function on the Math.round() page from MDN for this answer.

Related

toFixed method without rounding to five digit

I have a number var x = 2.305185185185195;
x = x.toFixed(5);
x = 2.30519 but I require this without rounding i.e. 2.30518
I read some thread with two decimal places but could not find for five decimal places.
Any help would be appreciated.
You can use an apropriate factor and floor it and return the result of the division.
Basically this solution moves the point to the left with a factor of 10^d and gets an integer of that and divided the value with the former factor to get the right digits.
function getFlooredFixed(v, d) {
return (Math.floor(v * Math.pow(10, d)) / Math.pow(10, d)).toFixed(d);
}
var x = 2.305185185185195;
document.write(getFlooredFixed(x, 5));
If you need only a "part" of a number with a floating point without rounding, you can just "cut" it:
function cutNumber(number, digitsAfterDot) {
const str = `${number}`;
return str.slice(0, str.indexOf('.') + digitsAfterDot + 1);
}
const x = 2.305185185185195;
console.log(cutNumber(x, 5)); // 2.30518
This method is fast (https://jsfiddle.net/93m8akzo/1/) and its execution time doesn't depend on number or digitsAfterDot values.
You can also "play around" with both functions in a given fiddle for a better understanding of what they do.
You can read more about slice() method here - MDN documentation
NOTE This function is only an example, don't use it in production applications.
You should definitely add input values validation and errors handling!
The Math.trunc() function returns the integer part of a number by
removing any fractional digits
So you can multiply the number by 10^n where n is the desired number of precision, truncate the decimal part using Math.trunc(), divide by the same number (10^n) and apply toFixed() to format it (in order to get the form of 2.30 instead of 2.3 for example)
var x = 2.305185185185195;
console.log((Math.trunc(x*100000)/100000).toFixed(5));
I have sorted it out by adding a small amount if the decimal is 5, then rounding as usual:
function(value, decimals) {
var decimals = decimals || 2;
if( isNaN(value) ){ return 0; }
var decimalPart = value.toString().trim().split('.').pop(),
extra = decimalPart.substr(decimals, decimalPart.length - decimals);
if( extra == '5' &&
decimalPart.length > decimals
){
value = parseFloat(value) + (1 / ( Math.pow(10, decimals + 5) ) );
}
return Number( parseFloat( value ).toFixed( decimals ) );
}

Math.abs() Limit the amount of deimals

I have scoured the internet and I haven't found a solution that really works for me, yet.
var tv = Length * Type;
if (tv < 0)
{
cForm.voltage.value = "-" + Math.abs(tv) + " V";
}
else...
Some of the calculations with these two numbers come out to about the 15th decimal for some reason. I would like to limit the decimal amount that is returned, and NOT allow the number to round up or down. On a calculator it only comes out to about the third decimal, but Math.abs() brings it too far out.
.toFixed() Doesn't work for me because if the number only has 2 decimals it will add additional zeros at the end. I only want to display up to the fourth if it is calculated.
Just expanding on #goto-0 s comment, with the correct # of decimal places.
var tv = Length * Type;
if (tv < 0)
{
cForm.voltage.value = "-" + (Math.round(Math.abs(tv) * 10000) / 10000) + " V";
}
else...
Here's the implementation as a function that truncates the extra decimal places. If you want to round the output you could just use Number.toPrecision().
function toFixedDecimals(num, maxDecimals) {
var multiplier = Math.pow(10, maxDecimals);
return Math.floor(num * multiplier) / multiplier
}
console.log(toFixedDecimals(0.123456789, 4));
console.log(toFixedDecimals(100, 4));
console.log(toFixedDecimals(100.12, 4));
I'm sure its not the most efficient approach but it is pretty brainless -
grab your result
split it into an array based on the decimal point
then trim the decimal part to two digits (or however many you would like).
concat the pieces back together
Sorry for the long variable names - just trying to make it clear what was happening : )
// your starting number - can be whatever you'd like
var number = 145.3928523;
// convert number to string
var number_in_string_form = String(number);
// split the number in an array based on the decimal point
var result = number_in_string_form.split(".");
// this is just to show you what values you end up where in the array
var digit = result[0];
var decimal = result[1];
// trim the decimal lenght to whatever you would like
// starting at the index 0 , take the next 2 characters
decimal = decimal.substr(0, 2);
// concat the digit with the decimal - dont forget the decimal point!
var finished_value = Number(digit + "." + decimal);
In this case the finished_value would = 145.39

How to get numbers with precision without round up or round down [duplicate]

This question already has answers here:
Truncate (not round off) decimal numbers in javascript
(32 answers)
Closed 8 years ago.
Im trying to get a number with precision to 2 decimals, for example this is what I want, if I have the numbers:
3.456 it must returns me 3.45
3.467 = 3.46
3.435 = 3.43
3.422 = 3.42
I don't want to round up or down or whatever just to get the numbers I see 2 places after .
Thanks
Okay, here is the answer
var a = 5.469923;
var truncated = Math.floor(a * 100) / 100; // = 5.46
Thanks everyone for helping.
Assuming Positive Numbers:
The code:
function roundDown(num,dec) {
return Math.floor(num*Math.pow(10,dec))/Math.pow(10,dec);
}
The test:
function test(num, expected) {
var val = roundDown(num,2);
var pass = val === expected;
var result = pass ? "PASS" : "FAIL";
var color = pass ? "GREEN" : "RED";
console.log("%c" + result + " : " + num + " : " + val, "background-color:" + color);
}
test(3.456, 3.45);
test(3.467, 3.46);
test(3.435, 3.43);
test(3.422, 3.42);
Basic idea:
Take number
Multiply the number to move decimal place to number of significant figures you want
Floor the number to remove the trailing numbers
Divide number back to get the correct value
If you want to have a trailing zero, you need to use toFixed(2) which will turn the number to a string.
function roundDown(num,dec) {
return Math.floor(num*Math.pow(10,dec))/Math.pow(10,dec).toFixed(2);
}
and the test cases would need to change to
test(3.456, "3.45");
test(3.467, "3.46");
test(3.435, "3.43");
test(3.422, "3.42");
Another option is a regular expression.
function roundDown(num,dec) {
var x = num.toString().match(/(\d*(\.\d{2}))?/);
return x ? parseFloat(x[0]) : "";
//return x ? parseFloat(x[0]).toFixed(2) : "";
}
Use String operation to achieve it.
var n = 4.56789;
var numbers = n.toString().split('.');
result = Number(numbers[0]+"."+numbers[1].substr(0,2));
alert(result);
Fiddle
You are looking at the number as if it were a string of digits, rather than a single value, so treat it like a string.-
function cutoff(n, cut){
var parts= String(n).split('.'), dec= parts[1];
if(!cut) return parts[0];
if(dec && dec.length>cut) parts[1]= dec.substring(0, cut);
return parts.join('.');
}
var n= 36.938;
cutoff(n,2)
/* returned value: (String)
36.93
*/
If you want a number, +cutoff(n,2) will do.
function truncateDec(num, decplaces) {
return (num*Math.pow(10,decplaces) - num*Math.pow(10,decplaces) % 1)/Math.pow(10,decplaces);
}
alert(truncateDec(105.678, 2)); // Returns 105.67
alert(truncateDec(105.678, 1)); // Returns 105.6
This could be simplified further if you do not require a dynamic number of decimal places
function truncateDec(num) {
return (num*100 - num*100 % 1)/100;
}
alert(truncateDec(105.678)); // Returns 105.67
How does it work?
The concept is that the main truncation works by getting the remainder from dividing the original decimal by 1. The remainder will be whatever is in the decimals places. The remainder operator is %
105.678 % 1 = 0.678
By subtracting this remainder from the original number, we will be left with only the integer.
105.678 - 0.678 = 105
To include x number of decimal places, we need to first multiply the original number by 10 to the power of that number of decimal places, thereby shifting the decimal backward by x positions. In this example, we will take x = 2.
105.678 * 10^2
= 105.678 * 100
= 10567.8
Now, we repeat the same procedure by subtracting the remainder again.
10567.8 % 1 = 0.8
10567.8 - 0.8 = 10567
And to return back to the number of places as requested, we divide it back by 10^x
10567 / 10^2
= 10567 / 100
= 105.67
Hope it helps!

Can I move a decimal in javascript without math?

I would love to be able to move a decimal point 2 places across an unknown amount of numbers without using math. I know that seems weird, but finite precision causes some shifts. My javascript is not strong, but I'd really like to learn how to chop up a number and do this if it's possible. So, I'm hoping you awesome folks can help.
The problem:
575/960 = 0.5989583333333334 using the console
I would like to make that a copy and pastable percentage like: 59.89583333333334%
If I use math and multiply by 100, it returns 59.895833333333336 because of finite precision
Is there a way to make that a string and just always move the decimal 2 places to the right to skip the math?
Here's a fiddle too, with the codes: http://jsfiddle.net/dandenney/W9fXz/
If you want to know why I need it and want the precision, it's for this little tool that I made for getting responsive percentages without using the calculator: http://responsv.com/flexible-math
If the original number is of this type of known structure and always has at least two digits to the right of the decimal, you can do it like this:
function makePercentStr(num) {
var numStr = num + "";
// if no decimal point, add .00 on end
if (numStr.indexOf(".") == -1) {
numStr += ".00";
} else {
// make sure there's at least two chars after decimal point
while (!numStr.match(/\.../)) {
numStr += "0";
}
}
return(numStr.replace(/\.(..)/, "$1.")
.replace(/^0+/, "") // trim leading zeroes
.replace(/\.$/, "") // trim trailing decimals
.replace(/^$/, "0") // if empty, add back a single 0
+ "%");
}
Working demo with test cases: http://jsfiddle.net/jfriend00/ZRNuw/
The question asks to solve the problem without Math but the below solution involves math. I am leaving it for just a reference
function convertToPercentage(num) {
//Changes the answer to string for checking
//the number of decimal places.
var numString = num + '';
var length = (numString).substring(numString.indexOf(".")+1).length;
//if the original decimal places is less then
//no need to display decimals as we are multiplying by 100
//else remove two decimals from the result
var precision = (length < 2 ? 0 : length-2);
//if the number never contained a decimal.
//Don't display decimal.
if(numString.indexOf(".") === -1) {
precision = 0;
}
return (num * 100).toFixed(precision) + "%";
}
Working jsFiddle here with same test cases as the accepted answer.
I've used this method because of the risk of floating errors:
const DECIMAL_SEP = '.';
function toPercent(num) {
const [integer, decimal] = String(num).split(DECIMAL_SEP);
// no decimal, just multiply by 100
if(typeof decimal === 'undefined') {
return num * 100;
}
const length = decimal.length;
if(length === 1) {
return Number(integer + decimal + '0');
}
if(length === 2) {
return Number(integer + decimal);
}
// more than 2 decimals, we shift the decimal separator by 2
return Number(integer + decimal.substr(0, 2) + DECIMAL_SEP + decimal.substr(2));
}
console.log(toPercent(10));
console.log(toPercent(1));
console.log(toPercent(0));
console.log(toPercent(0.01));
console.log(toPercent(0.1));
console.log(toPercent(0.12));
console.log(toPercent(0.123));
console.log(toPercent(12.3456));

How to perform an integer division, and separately get the remainder, in JavaScript?

In JavaScript, how do I get:
The whole number of times a given integer goes into another?
The remainder?
For some number y and some divisor x compute the quotient (quotient)[1] and remainder (remainder) as:
const quotient = Math.floor(y/x);
const remainder = y % x;
Example:
const quotient = Math.floor(13/3); // => 4 => the times 3 fits into 13
const remainder = 13 % 3; // => 1
[1] The integer number resulting from the division of one number by another
I'm no expert in bitwise operators, but here's another way to get the whole number:
var num = ~~(a / b);
This will work properly for negative numbers as well, while Math.floor() will round in the wrong direction.
This seems correct as well:
var num = (a / b) >> 0;
I did some speed tests on Firefox.
-100/3 // -33.33..., 0.3663 millisec
Math.floor(-100/3) // -34, 0.5016 millisec
~~(-100/3) // -33, 0.3619 millisec
(-100/3>>0) // -33, 0.3632 millisec
(-100/3|0) // -33, 0.3856 millisec
(-100-(-100%3))/3 // -33, 0.3591 millisec
/* a=-100, b=3 */
a/b // -33.33..., 0.4863 millisec
Math.floor(a/b) // -34, 0.6019 millisec
~~(a/b) // -33, 0.5148 millisec
(a/b>>0) // -33, 0.5048 millisec
(a/b|0) // -33, 0.5078 millisec
(a-(a%b))/b // -33, 0.6649 millisec
The above is based on 10 million trials for each.
Conclusion: Use (a/b>>0) (or (~~(a/b)) or (a/b|0)) to achieve about 20% gain in efficiency. Also keep in mind that they are all inconsistent with Math.floor, when a/b<0 && a%b!=0.
ES6 introduces the new Math.trunc method. This allows to fix #MarkElliot's answer to make it work for negative numbers too:
var div = Math.trunc(y/x);
var rem = y % x;
Note that Math methods have the advantage over bitwise operators that they work with numbers over 231.
I normally use:
const quotient = (a - a % b) / b;
const remainder = a % b;
It's probably not the most elegant, but it works.
var remainder = x % y;
return (x - remainder) / y;
You can use the function parseInt to get a truncated result.
parseInt(a/b)
To get a remainder, use mod operator:
a%b
parseInt have some pitfalls with strings, to avoid use radix parameter with base 10
parseInt("09", 10)
In some cases the string representation of the number can be a scientific notation, in this case, parseInt will produce a wrong result.
parseInt(100000000000000000000000000000000, 10) // 1e+32
This call will produce 1 as result.
Math.floor(operation) returns the rounded down value of the operation.
Example of 1st question:
const x = 5;
const y = 10.4;
const z = Math.floor(x + y);
console.log(z);
Example of 2nd question:
const x = 14;
const y = 5;
const z = Math.floor(x % y);
console.log(x);
JavaScript calculates right the floor of negative numbers and the remainder of non-integer numbers, following the mathematical definitions for them.
FLOOR is defined as "the largest integer number smaller than the parameter", thus:
positive numbers: FLOOR(X)=integer part of X;
negative numbers: FLOOR(X)=integer part of X minus 1 (because it must be SMALLER than the parameter, i.e., more negative!)
REMAINDER is defined as the "left over" of a division (Euclidean arithmetic). When the dividend is not an integer, the quotient is usually also not an integer, i.e., there is no remainder, but if the quotient is forced to be an integer (and that's what happens when someone tries to get the remainder or modulus of a floating-point number), there will be a non-integer "left over", obviously.
JavaScript does calculate everything as expected, so the programmer must be careful to ask the proper questions (and people should be careful to answer what is asked!) Yarin's first question was NOT "what is the integer division of X by Y", but, instead, "the WHOLE number of times a given integer GOES INTO another". For positive numbers, the answer is the same for both, but not for negative numbers, because the integer division (dividend by divisor) will be -1 smaller than the times a number (divisor) "goes into" another (dividend). In other words, FLOOR will return the correct answer for an integer division of a negative number, but Yarin didn't ask that!
gammax answered correctly, that code works as asked by Yarin. On the other hand, Samuel is wrong, he didn't do the maths, I guess, or he would have seen that it does work (also, he didn't say what was the divisor of his example, but I hope it was 3):
Remainder = X % Y = -100 % 3 = -1
GoesInto = (X - Remainder) / Y = (-100 - -1) / 3 = -99 / 3 = -33
By the way, I tested the code on Firefox 27.0.1, it worked as expected, with positive and negative numbers and also with non-integer values, both for dividend and divisor. Example:
-100.34 / 3.57: GoesInto = -28, Remainder = -0.3800000000000079
Yes, I noticed, there is a precision problem there, but I didn't had time to check it (I don't know if it's a problem with Firefox, Windows 7 or with my CPU's FPU). For Yarin's question, though, which only involves integers, the gammax's code works perfectly.
const idivmod = (a, b) => [a/b |0, a%b];
there is also a proposal working on it
Modulus and Additional Integer Math
Alex Moore-Niemi's comment as an answer:
For Rubyists here from Google in search of divmod, you can implement it as such:
function divmod(x, y) {
var div = Math.trunc(x/y);
var rem = x % y;
return [div, rem];
}
Result:
// [2, 33]
If you need to calculate the remainder for very large integers, which the JS runtime cannot represent as such (any integer greater than 2^32 is represented as a float and so it loses precision), you need to do some trick.
This is especially important for checking many case of check digits which are present in many instances of our daily life (bank account numbers, credit cards, ...)
First of all you need your number as a string (otherwise you have already lost precision and the remainder does not make sense).
str = '123456789123456789123456789'
You now need to split your string in smaller parts, small enough so the concatenation of any remainder and a piece of string can fit in 9 digits.
digits = 9 - String(divisor).length
Prepare a regular expression to split the string
splitter = new RegExp(`.{1,${digits}}(?=(.{${digits}})+$)`, 'g')
For instance, if digits is 7, the regexp is
/.{1,7}(?=(.{7})+$)/g
It matches a nonempty substring of maximum length 7, which is followed ((?=...) is a positive lookahead) by a number of characters that is multiple of 7. The 'g' is to make the expression run through all string, not stopping at first match.
Now convert each part to integer, and calculate the remainders by reduce (adding back the previous remainder - or 0 - multiplied by the correct power of 10):
reducer = (rem, piece) => (rem * Math.pow(10, digits) + piece) % divisor
This will work because of the "subtraction" remainder algorithm:
n mod d = (n - kd) mod d
which allows to replace any 'initial part' of the decimal representation of a number with its remainder, without affecting the final remainder.
The final code would look like:
function remainder(num, div) {
const digits = 9 - String(div).length;
const splitter = new RegExp(`.{1,${digits}}(?=(.{${digits}})+$)`, 'g');
const mult = Math.pow(10, digits);
const reducer = (rem, piece) => (rem * mult + piece) % div;
return str.match(splitter).map(Number).reduce(reducer, 0);
}
If you are just dividing with powers of two, you can use bitwise operators:
export function divideBy2(num) {
return [num >> 1, num & 1];
}
export function divideBy4(num) {
return [num >> 2, num & 3];
}
export function divideBy8(num) {
return [num >> 3, num & 7];
}
(The first is the quotient, the second the remainder)
function integerDivison(dividend, divisor){
this.Division = dividend/divisor;
this.Quotient = Math.floor(dividend/divisor);
this.Remainder = dividend%divisor;
this.calculate = ()=>{
return {Value:this.Division,Quotient:this.Quotient,Remainder:this.Remainder};
}
}
var divide = new integerDivison(5,2);
console.log(divide.Quotient) //to get Quotient of two value
console.log(divide.division) //to get Floating division of two value
console.log(divide.Remainder) //to get Remainder of two value
console.log(divide.calculate()) //to get object containing all the values
You can use ternary to decide how to handle positive and negative integer values as well.
var myInt = (y > 0) ? Math.floor(y/x) : Math.floor(y/x) + 1
If the number is a positive, all is fine. If the number is a negative, it will add 1 because of how Math.floor handles negatives.
This will always truncate towards zero.
Not sure if it is too late, but here it goes:
function intdiv(dividend, divisor) {
divisor = divisor - divisor % 1;
if (divisor == 0) throw new Error("division by zero");
dividend = dividend - dividend % 1;
var rem = dividend % divisor;
return {
remainder: rem,
quotient: (dividend - rem) / divisor
};
}
Calculating number of pages may be done in one step:
Math.ceil(x/y)
Here is a way to do this. (Personally I would not do it this way, but thought it was a fun way to do it for an example) The ways mentioned above are definitely better as this calls multiple functions and is therefore slower as well as takes up more room in your bundle.
function intDivide(numerator, denominator) {
return parseInt((numerator/denominator).toString().split(".")[0]);
}
let x = intDivide(4,5);
let y = intDivide(5,5);
let z = intDivide(6,5);
console.log(x);
console.log(y);
console.log(z);

Categories

Resources