represent decimal numbers in javascript as "%g" formatting in C - javascript

I have a number generated as a finite decimal:
var x = k * Math.pow(10,p)
with k and p integers. Is there a simple way to convert it to an exact string representation?
If I use implict string conversion I get ugly results:
""+ 7*Math.pow(10,-1)
gives
"0.7000000000000001"
I tried using .toFixed and .toPrecision but it is very difficult to find the correct precision to use depending on k and p. Is there a way to get the good old "%g" formatting of C language? Maybe I should resort to an external library?

One can use math.format from math.js library:
math.format(7 * Math.pow(10, -1), {precision: 14});
gives
"0.7"

You can create your own floor function like this, with option accuracy
function fixRound(number, accuracy) {
return ""+Math.floor(number * (accuracy || 1)) / accuracy || 1;
}
let num = 7 * Math.pow(10, -1);
console.log(fixRound(num, 1000))

Related

How to change the limit of toFixed() function in js?

I want to be able to use standard toFixed() function with an arbitrary number (official allows using values between 0 and 20)
I don't know how to change the limit, so I found this library allowing to specify an arbitrary number:
https://github.com/MikeMcl/big.js/blob/master/big.js
I don't want to use the whole library just to able to run this one function. Please help me to understand how does this library implementing this arbitrary length toFixed() function?
update:
For example in python, a module called Decimal can calculate as many floating digits as you want:
>>> num1 = 4857932878236943867839468934782
>>> num2 = 1328768938470-2699462978
>>> result = Decimal(num1) / Decimal(num2)
>>> result
3663407512215411920.125441595041830470639118971082230413476294397448265790489938870721
Or you can just use simple function
var numberStr = '20.83953272434765327423485345342342345';
function toFixed(nbr, precision) {
let nSplit = nbr.split('.');
return nSplit[0] + '.' + nSplit[1].substring(0, precision);
}
console.log( toFixed(numberStr, 22) );
//or you could extend String.prototype as
String.prototype.toLongFixed = function(precission) {
let split = this.split('.');
return split[0] + '.' + split[1].substring(0, precission);
}
console.log( numberStr.toLongFixed(33) );

How to remove trailing decimals without rounding up?

For example, I have a number 123.429. How can I remove the trailing decimals without rounding up to two decimal place.
Hence, I need the number to be up to two d.p. i.e 123.42.
Definitely toFixed() method or Math.round(num * 100) / 100 cannot be used in this situation.
The function you want is Math.floor(x) to remove decimals without rounding up (so floor(4.9) = 4).
var number = Math.floor(num * 100) / 100;
Edit: I want to update my answer because actually, this rounds down with negative numbers:
var Math.floor(-1.456 * 100) / 100;
-1.46
However, since Javascript 6, they have introduced the Math.trunc() function which truncates to an int without rounding, as expected. You can use it the same way as my proposed usage of Math.floor():
var number = Math.trunc(num * 100) / 100;
Alternatively, the parseInt() method proposed by awe works as well, although requires a string allocation.
var number = parseInt('' + (num * 100)) / 100;
You can convert it to a string and then simply truncate the string two places after the decimal, e.g.:
var s = String(123.429);
s.substring(0, s.indexOf('.') + 3); // "123.42"
Please note that there's no guarantee if you convert that final string back into a number that it'll be exactly representable to those two decimal places - computer floating point math doesn't work that way.
another v. cool solution is by using | operator
let num = 123.429 | 0
let num = 123.429 | 0
console.log(num);
let's get the variable name as "num"
var num = 123.429;
num=num*100;
num=num.toString();
num=num.split(".");
num=parseInt(num[0]);
num=num/100;
value of the num variable will be 12.42
Try this
number = parseFloat(number).toFixed(12);
number = number.substring(0, number.indexOf('.') + 3);
return parseFloat(number);
Not the fastest solution but the only one that handles an edge case like 0.0006*10000 = 5.999999999 properly, i.e. if you want to truncate to 4 decimal places and the value is exactly 0.0006, then using Math.trunc(0.0006 * (10 ** 4))/(10 ** 4) gives you 0.0005.

Convert A Large Integer To a Hex String In Javascript

I need to find a way to convert a large number into a hex string in javascript. Straight off the bat, I tried myBigNumber.toString(16) but if myBigNumber has a very large value (eg 1298925419114529174706173) then myBigNumber.toString(16) will return an erroneous result, which is just brilliant. I tried writing by own function as follows:
function (integer) {
var result = '';
while (integer) {
result = (integer % 16).toString(16) + result;
integer = Math.floor(integer / 16);
}
}
However, large numbers modulo 16 all return 0 (I think this fundamental issue is what is causing the problem with toString. I also tried replacing (integer % 16) with (integer - 16 * Math.floor(integer/16)) but that had the same issue.
I have also looked at the Big Integer Javascript library but that is a huge plugin for one, hopefully relatively straightforward problem.
Any thoughts as to how I can get a valid result? Maybe some sort of divide and conquer approach? I am really rather stuck here.
Assuming you have your integer stored as a decimal string like '1298925419114529174706173':
function dec2hex(str){ // .toString(16) only works up to 2^53
var dec = str.toString().split(''), sum = [], hex = [], i, s
while(dec.length){
s = 1 * dec.shift()
for(i = 0; s || i < sum.length; i++){
s += (sum[i] || 0) * 10
sum[i] = s % 16
s = (s - sum[i]) / 16
}
}
while(sum.length){
hex.push(sum.pop().toString(16))
}
return hex.join('')
}
The numbers in question are above javascript's largest integer. However, you can work with such large numbers by strings and there are some plugins which can help you do this. An example which is particularly useful in this circumstance is hex2dec
The approach I took was to use the bignumber.js library and create a BigNumber passing in the value as a string then just use toString to convert to hex:
const BigNumber = require('bignumber.js');
const lrgIntStr = '1298925419114529174706173';
const bn = new BigNumber(lrgIntStr);
const hex = bn.toString(16);

javascript division giving wrong answer? [duplicate]

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.

Converting a double to an int in Javascript without rounding

In C# the following code returns 2:
double d = 2.9;
int i = (int)d;
Debug.WriteLine(i);
In Javascript, however, the only way of converting a "double" to an "int" that I'm aware of is by using Math.round/floor/toFixed etc. Is there a way of converting to an int in Javascript without rounding? I'm aware of the performance implications of Number() so I'd rather avoid converting it to a string if at all possible.
Use parseInt().
var num = 2.9
console.log(parseInt(num, 10)); // 2
You can also use |.
var num = 2.9
console.log(num | 0); // 2
I find the "parseInt" suggestions to be pretty curious, because "parseInt" operates on strings by design. That's why its name has the word "parse" in it.
A trick that avoids a function call entirely is
var truncated = ~~number;
The double application of the "~" unary operator will leave you with a truncated version of a double-precision value. However, the value is limited to 32 bit precision, as with all the other JavaScript operations that implicitly involve considering numbers to be integers (like array indexing and the bitwise operators).
edit — In an update quite a while later, another alternative to the ~~ trick is to bitwise-OR the value with zero:
var truncated = number|0;
Similar to C# casting to (int) with just using standard lib:
Math.trunc(1.6) // 1
Math.trunc(-1.6) // -1
Just use parseInt() and be sure to include the radix so you get predictable results:
parseInt(d, 10);
There is no such thing as an int in Javascript. All Numbers are actually doubles behind the scenes* so you can't rely on the type system to issue a rounding order for you as you can in C or C#.
You don't need to worry about precision issues (since doubles correctly represent any integer up to 2^53) but you really are stuck with using Math.floor (or other equivalent tricks) if you want to round to the nearest integer.
*Most JS engines use native ints when they can but all in all JS numbers must still have double semantics.
A trick to truncate that avoids a function call entirely is
var number = 2.9
var truncated = number - number % 1;
console.log(truncated); // 2
To round a floating-point number to the nearest integer, use the addition/subtraction trick. This works for numbers with absolute value < 2 ^ 51.
var number = 2.9
var rounded = number + 6755399441055744.0 - 6755399441055744.0; // (2^52 + 2^51)
console.log(rounded); // 3
Note:
Halfway values are rounded to the nearest even using "round half to even" as the tie-breaking rule. Thus, for example, +23.5 becomes +24, as does +24.5. This variant of the round-to-nearest mode is also called bankers' rounding.
The magic number 6755399441055744.0 is explained in the stackoverflow post "A fast method to round a double to a 32-bit int explained".
// Round to whole integers using arithmetic operators
let trunc = (v) => v - v % 1;
let ceil = (v) => trunc(v % 1 > 0 ? v + 1 : v);
let floor = (v) => trunc(v % 1 < 0 ? v - 1 : v);
let round = (v) => trunc(v < 0 ? v - 0.5 : v + 0.5);
let roundHalfEven = (v) => v + 6755399441055744.0 - 6755399441055744.0; // (2^52 + 2^51)
console.log("number floor ceil round trunc");
var array = [1.5, 1.4, 1.0, -1.0, -1.4, -1.5];
array.forEach(x => {
let f = x => (x).toString().padStart(6," ");
console.log(`${f(x)} ${f(floor(x))} ${f(ceil(x))} ${f(round(x))} ${f(trunc(x))}`);
});
As #Quentin and #Pointy pointed out in their comments, it's not a good idea to use parseInt() because it is designed to convert a string to an integer. When you pass a decimal number to it, it first converts the number to a string, then casts it to an integer. I suggest you use Math.trunc(), Math.floor(), ~~num, ~~v , num | 0, num << 0, or num >> 0 depending on your needs.
This performance test demonstrates the difference in parseInt() and Math.floor() performance.
Also, this post explains the difference between the proposed methods.
What about this:
if (stringToSearch.IndexOfAny( ".,;:?!".ToCharArray() ) == -1) { ... }
I think that the easiest solution is using the bitwise not operator twice:
const myDouble = -66.7;
console.log(myDouble); //-66.7
const myInt = ~~myDouble;
console.log(myInt); //-66
const myInt = ~~-myDouble;
console.log(myInt); //66

Categories