How to round down integer to all zeros behind first number - javascript

For example, I need to round number 6588 => 6000 , 1285000 => 1000000
I can't find any Math.ceil , Math.floor methods that can achieve this.

You can divide by the highest power of ten, floor it, then multiply back by the highest power of ten. Some other answers are manipulating string, but IMO this is the simplest and easiest to read code. Like this:
function roundDown(num) {
let powerOfTen = num.toString().length - 1;
num /= (10**powerOfTen);
return Math.floor(num) * (10**powerOfTen);
}
console.log(roundDown(6588)) // => 6000
console.log(roundDown(1285000)) // => 1000000
This is roughly the same procedure that Math.floor() uses, as described in this MDN article;

another variant is just work on string level, instead of numbers to avoid any floating point problems
function roundToFirst(n) {
return (''+n).split('').map((c, i) => i > 0 ? '0' : c).join('');
}
console.log(roundToFirst(6588)); // 6000
console.log(roundToFirst(1285000)); // 1000000

You can convert your number to a string and simply append zeros to match the number's length.
const roundDown = (num) => {
num = num.toString();
return (num[0] + new Array(num.length).join('0'));
}
console.log(roundDown(6588))
console.log(roundDown(0))

A short and easy way is to take the first digit and padEnd the rest
const roundDown = num => {
num = String(num)
return +num[0].padEnd(num.length, "0")
}
console.log(roundDown(6588))
console.log(roundDown(1285000))
References
padEnd

Related

How to implement an algorithm to detect if a number has 2 consecutive digits?

I want to create a function that returns true if a number has consecutive digits or not,
example:
if the input is 11, it will return true
if the input is 21 it will return false
if the input is 323 it will return false because even though we have 3 repeated, they are not consecutive
My solution right now is to transform the number into an array and loop through the number one by one, if the next number is equal to the current number then we just return true. But this has a complexity time of O(n) and I was wondering if anyone can come with a better solution.
Thank you
There is an arguably better solution where you don't need to convert the number into a string or array of numbers/character. It works as follows:
Initialize a variable curr to -1.
Run a loop while num > 0 and do the following:
next_curr = num % 10
if next_curr == curr: return true
curr = next_curr
num = num / 10 (integer division)
If the loop completes, return false.
This is a one pass O(log n) time complexity algorithm where n is the input number. The space complexity is O(1)
Note that while your algorithm was also O(log n) time complexity, it did 2 passes, and had a space complexity of O(log n) too.
I haven't written JS for some time now, but here's a possible implementation of the above algorithm in JS:
function sameAdjacentDigits(num) {
// to deal with negative numbers and
// avoid potential problems when using Math.floor later
num = Math.abs(num)
let curr = -1
while (num > 0) {
const nextCurr = num % 10
if (nextCurr == curr) return true
curr = nextCurr
num = Math.floor(num / 10)
}
return false
}
Use some regex, and then check what was found via the matcher
numbers_match = /(00|11|22|33|44|55|66|77|88|99)/;
numbers_match.match("11")
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
Easiest way to execute this is by using regex. Not sure what would be effectiveness of algorithm, but solution could be
/(\d)\1/
Inspired from #Tschallacka's answer:
let numbers = [11,21,323];
let result = numbers.map(n=>{
let test = n.toString().match(/(00|11|22|33|44|55|66|77|88|99)/);
return test != null;
})
console.log(result);

How to reverse numeric value having scientific notation in nodeJS?

I want to understand best way to reverse an integer (both positive and negative) in NodeJS 12. Can we do this without converting number to string? It should also support scientific notation numbers like 1e+10 which is 10000000000.
Input/Expected Output
500 = 5
-94 = -49
1234 = 4321
-1 = -1
1e+10 = 1
123.45e+10 = 54321
This is the answer I could come up with but I feel there might be better way. I didn't like the way I had to convert the integer to string, reverse it and again convert it back to integer.
parseInt(Math.sign(num) * parseInt(Math.abs(num).toString().split("").reverse().join("")))
function reverseNum(num) {
return (
parseFloat(
num
.toString()
.split('')
.reverse()
.join('')
) * Math.sign(num)
)
}
I hope this one line function solves your use-case
// The Math.sign() function returns either a positive or negative +/- 1,
// indicating the sign of a number passed into the argument.
function reverseInt(n) {
return parseInt(n.toString().split('').reverse().join('')) * Math.sign(n)
}
console.log(reverseInt(500));
console.log(reverseInt(-94));
console.log(reverseInt(1234));

Convert whole number to one decimal in JavaScript

I got this issue.
I want to convert integer 71 (type number) to one decimal, meaning 71.0
but I need it to stay of type number.
Searched and the only solution I found was to use toFixed(1) and then parseFloat on
the result, and that does returns a number but 71, without the decimal.
const float = (num) => {
let fixed = (num).toFixed(1)
let float = parseFloat(fixed)
return float
}
float(71)
How should I do it?
This makes no sense, because an integer (whole number) will almost always equal its floating-point equivalent, unless there is a some odd precision behavior.
71 === 71.0
71 === 71.00
...
71 !== 71.000000001
Did you want to truncate a floating number using precision?
const truncateFloat = (n, p = 0) => parseFloat(n.toFixed(p));
// Truncate an irrational number (PI)
console.log(truncateFloat(Math.PI, 2) === 3.14) // true
Remove the parseFloat(fixed) and keep it as below
const float = (num) => {
let fixed = (num).toFixed(2)
//let float = parseFloat(fixed)
return float
}
float(71)
use toFixed(n) where n is the number of 10th places after the decimal.
You have stated that you need to keep it as number at the end but the thing is, if the decimals are 0, it will always round up to a whole number. So you may want to rather consider adding the toFixed(n) at the point of printing to the screen so they always print with that extra.
========= UPDATE
I just found a cleaner solution. consider the below with a link to the solution
const float = (num) => {
tmp = '0.00';
tmp = (+tmp + num).toFixed(2);
return tmp
}
float(71)
reference: how to get a float using parseFloat(0.00)

Sum Strings as Numbers

I am trying to solve a kata that seems to be simple on codewars but i seem to not be getting it right.
The instruction for this is as simple as below
Given the string representations of two integers, return the string representation of the sum of those integers.
For example:
sumStrings('1','2') // => '3'
A string representation of an integer will contain no characters besides the ten numerals "0" to "9".
And this is what i have tried
function sumStrings(a,b) {
return ((+a) + (+b)).toString();
}
But the results solves all except two and these are the errors i get
sumStrings('712569312664357328695151392', '8100824045303269669937') - Expected: '712577413488402631964821329', instead got: '7.125774134884027e+26'
sumStrings('50095301248058391139327916261', '81055900096023504197206408605') - Expected: '131151201344081895336534324866', instead got: '1.3115120134408189e+29'
I don't seem to understand where the issues is from. Any help would help thanks.
The value you entered is bigger than the int type max value. You can try changing your code to:
function sumStrings(a,b) {
return ((BigInt(a)) + BigInt(b)).toString();
}
This way it should return the right value
You could pop the digits and collect with a carry over for the next digit.
function add(a, b) {
var aa = Array.from(a, Number),
bb = Array.from(b, Number),
result = [],
carry = 0,
i = Math.max(a.length, b.length);
while (i--) {
carry += (aa.pop() || 0) + (bb.pop() || 0);
result.unshift(carry % 10);
carry = Math.floor(carry / 10);
}
while (carry) {
result.unshift(carry % 10);
carry = Math.floor(carry / 10);
}
return result.join('');
}
console.log(add('712569312664357328695151392', '8100824045303269669937'));
console.log(add('50095301248058391139327916261', '81055900096023504197206408605'));
The problem is that regular javascript integers are not having enough space to store that much big number, So it uses the exponential notation to not lose its precision
what you can do is split each number into parts and add them separately,
one such example is here SO answer
My solution is:
function sumStrings(a,b) {
return BigInt(a) + BigInt(b) + ''
}
Converting from a string to a number or vice versa is not perfect in any language, they will be off by some digits. This doesn't seem to affect small numbers, but it affects big numbers a lot.
The function could go like this.
function sumStrings(a, b) {
return (BigInt(a) + BigInt(b)).toString() // or parseInt for both
}
However, it's still not perfect since if we try to do:
console.log((4213213124214211215421314213.0 + 124214321214213434213124211.0) === sumStrings('4213213124214211215421314213', '124214321214213434213124211'))
The output would be false.

Limit decimal places to specific situations (not round)

Im looking to limit a number do 2 decimal places, but only when the rest is zero. I dont want to round the numbers.
I tried using this example
(1.0000).toFixed(2)
the result would be 1.00, but if i have a number like (1.0030).toFixed(2), the result should be 1.003.
I tried using parseFloat with a combination of toFixed but doesn´t get the result i want.
Is there any function in javascript that does what im trying to achieve.
So you want a minimum of two decimals? Here's one way:
function toMinTwoDecimals(numString) {
var num = parseFloat(numString);
return num == num.toFixed(2) ? num.toFixed(2) : num.toString();
}
Examples:
toMinTwoDecimals("1.0030"); // returns "1.003"
toMinTwoDecimals("1.0000"); // returns "1.00"
toMinTwoDecimals("1"); // returns "1.00"
toMinTwoDecimals("-5.24342234"); // returns "-5.24342234"
In case you want to leave numbers with less than two decimals untouched, use this instead:
function toMinTwoDecimals(numString) {
var num = parseFloat(numString);
// Trim extra zeros for numbers with three or more
// significant decimals (e.g. "1.0030" => "1.003")
if (num != num.toFixed(2)) {
return num.toString();
}
// Leave numbers with zero or one decimal untouched
// (e.g. "5", "1.3")
if (numString === num.toFixed(0) || numString === num.toFixed(1)) {
return numString;
}
// Limit to two decimals for numbers with extra zeros
// (e.g. "1.0000" => "1.00", "1.1000000" => "1.10")
return num.toFixed(2);
}

Categories

Resources