Error in Function to Determine number of digits in a number - javascript

I have a simple javascript function that tells me how many digits are in a number.
My Problem: On the last line I get a compiler error saying "Missing last ')' parenthisis". I am altering a snippet I found through google & it uses the function Math.log10() but I am not sure a function like this exists?
Can you help me to determine the number of digits in a number (eg 1000 = 4, 10 = 2, etc.)?
function getDigitCount( number )
{
//return ((number ==0) ? 1 : (int)Math.log10(number) + 1);
if ( (number == 0) )
{
return 1;
}
else return ((int)Math.log10(number) + 1);
}

You cannot cast to an int in Javascript. Instead, use Math.floor. Also, divide by Math.log(10) (or Math.LN10) instead of using Math.log10() to find the base 10 logarithm of a number.:
else return (Math.floor(Math.log(number)/Math.log(10)) + 1);

You may try this:
Assuming that "number" is a positive integer value
function getDigitCount(number)
{
var c = "x" + number;
return c.length -1;
}

Related

Making a thousands (k) convertor function in Javascript without rounding and NOT remove .0 from end

I am trying to make a simple 1000 to k convertor function in JS that will take a number and convert it into thousands/k. I'm having trouble getting the .toFixed(1) working properly.
I don't want it to round up and I want it to show one decimal place UNLESS that decimal is a 0. A few examples of the returns I am looking to produce are:
1100 -> 1.1K
1199 -> 1.1K
9999 -> 9.9K
10900 -> 10.9K
10999 -> 10.9K
JS
function kConvertor(num) {
return num <= 999 ? num : (num/1000).toFixed(1) + 'k'
}
This returns 10.0k which hits both cases that I do not want (9.9k).
What am I doing wrong here?
I tried adding a parseInt() and .replace('.0', '') to the end and that didn't work.
function kConvertor(num) {
return num <= 999 ? num : parseInt((num/1000)).toFixed(1).replace('.0', '') + 'k'
}
This just returns 9k
This works by using math operators to correctly round down to the nearest 10th of a K, and then uses .toFixed(1) to perform the string manipulation necessary to strip .0 from the result:
function kConverter(num) {
return num <= 999 ? num : (0.1 * Math.floor(num / 100)).toFixed(1).replace('.0','') + 'k'
}
NB: it's not good practise to have the function return a number for <= 999, or a string otherwise. Unexpected result types is the cause of the vast majority of the "WAT?!" moments from the famous video. Always ensure that your return types are consistent:
function kConverter(num) {
if (num < 1000) {
return number.toFixed(0); // assuming an integer
} else {
const s = (0.1 * Math.floor(num / 100)).toFixed(1);
return s.replace('.0', '') + 'k';
}
}

How can I clean up this code and write it more eloquently?

I'm working on some practice problems using higher- order functions and while I was able to solve this problem. I can't help but think this code is ugly and not the most eloquent it could be. Is there a way to combined map and reduce is a cleaner way than I have done ? Additionally, is there any other methods or improvements I could have used here ? I'm just looking to get better and any feedback would be appreciated.
Problem: Given a number, "sumDigits" returns the sum of all its digits.If the number is negative, the first digit should count as negative.
function sumDigits(num) {
//create array of number char
var string = num.toString().split('');
//if first char is negative symbol let the first numeric element be negative
if (string[0] === "-") {
string[1] = '-' + string[1];
string.shift();
}
//convert string to int
var toInteger = string.map(function(x) {
return Number(x);
});
//get sum
return toInteger.reduce(function(sum, current) {
sum += current;
return sum;
})
}
sumDigits(-316);
You don't need to use map at all, if you convert to number inside the reduce. Here I used the unary + operator to convert the string to a number instead of the Number constructor, but that is not better than the Number constructor, just a habit:
function sumDigits ( num ) {
const chars = num.toString( ).split( '' );
// Subtract first digit if the string starts with a '-'
// Needs to be subtracted twice, since it is included in the sum
return ( chars[0] === '-' ? -2*chars[1] : +chars[0] ) +
chars.slice( 1 ).reduce( (sum, value) => sum + +value, 0 )
;
}

Truncating a String in Javascript (with constraints)

I'm working on this coding challenge from freecodecamp https://www.freecodecamp.com/challenges/truncate-a-string.
To complete this my code must fulfil the following 3 conditions:
Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending.
The inserted three dots at the end should also add to the string length.
However if the given maximum string length is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string.
I'm able to fulfil the first 2 conditions, but for some reason my code throws up an error when I give a test case where length of the string is less than or equal to 3...
Example:
truncateString("Absolutely Longer", 2) should return "Ab..." but instead returns "Absolutely Longe..."
Please help. My code is at https://gist.github.com/adityatejas/7857c0866f67783e71a1c9d60d3beed8.
function truncateString(str, num)
{
var truncatedStr = '';
if (str.length > num)
{
truncatedStr = str.slice(0, num-3) + "...";
return truncatedStr;
}
else if (num <= 3)
{
truncatedStr = str.slice(0, num) + "...";
return truncatedStr;
}
else return str;
}
truncateString("Adi", 1);
You want to create a function that takes in two parameters, a string of your choice and a maximum length. Based on the conditions, we need three scenarios.
When the given string exceeds the maximum and the maximum is less than or equal to 3. In this case, the ellipsis is not added to the end of the string. We take a slice of the string from the first character (position zero) until three less than the max and add the ellipses.
When the given string exceeds the maximum and the maximum is greater than 3. In this case, our strings inherently get longer. We update the slice parameters to go from the first index to the length of the string and add the ellipses on top of that.
Otherwise, just return the string as it is, because it does not exceed the maximum length.
var truncatedString = document.getElementById("truncated-string");
function truncateString(myString, strLength) {
if (myString.length > strLength) {
if (strLength <= 3) {
return myString.slice(0, strLength - 3) + "...";
}
else {
return myString.slice(0, strLength) + "...";
}
}
else {
return myString;
}
}
var userInput = prompt("Please enter a string");
var lengthLimit = prompt("Enter a maximum length");
truncatedString.innerHTML = truncateString(userInput, lengthLimit);
<p id="truncated-string"></p>
You could use a conditional (ternary) operator ?: and String#slice
function truncateString(str, num) {
return str.length > num ?
str.slice(0, num > 3 ? num - 3 : num) + "..." :
str;
}
console.log(truncateString("Abcdefghijk", 5));
console.log(truncateString("A-", 1));
console.log(truncateString("Alpha", 5));
console.log(truncateString("Beta", 5));
console.log(truncateString("Epsilon", 3));
Here is a simple solution:
function truncateString(str, num) {
if (str.length > num) {
return str.slice(0, num) + "...";}
else {
return str;}}

Function that returns arbitrary decimal place on javascript

I want to make some function on javascript,
that receives some number and position number n and returns its nth decimal place.
That is,
nthdigit(3.5852,2) = 8
nthdigit(3.5852,3) = 5
nthdigit(3.5852,5) = 0
nthdigit(9.772,1) = 7
How can I do this correctly? Thanks.
Pure math solution:
function decimaldigit(num, n) {
return Math.floor(num * Math.pow(10, n)) % 10;
}
Convert the number to a String, split it on the decimal ., take the character you want and convert it back to a number.
function nthdigit(number, i) {
var afterDecimal = number.toString().split(".")[1];
return parseInt(afterDecimal.charAt(i-1));
}
I've chosen charAt(i-1) because character are counted starting 0 and it feels more natural in this case when you want the first number to put in 1.
This should be very easy to solve:
var nthdigit function(decimal, n)
{
var dec = '' + decimal; //convert to string
var decimalString = dec.split('.')[1]; //covert to array, take element with index [1]
var decimalPlaces = decimalSting.split(''); //covert to array
return parseInt(decimalPlaces( n-1 )); //1. decimalPlace has index 0
}
Another pure math solution, with better precision for high numbers and correct handling of negative numbers:
function nthdigit(num, n) {
return n ? nthdigit((num % 1) * 10, n-1) : Math.trunc(num);
}
using Math.trunc:
if (typeof Math.trunc != "function")
Math.trunc = function trunc(value) {
return value === 0 ? value : !isFinite(value) ? value : value | 0;
}

Pad a number with leading zeros in JavaScript [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 3 years ago.
In JavaScript, I need to have padding.
For example, if I have the number 9, it will be "0009". If I have a number of say 10, it will be "0010". Notice how it will always contain four digits.
One way to do this would be to subtract the number minus 4 to get the number of 0s I need to put.
Is there was a slicker way of doing this?
ES2017 Update
You can use the built-in String.prototype.padStart()
n = 9;
String(n).padStart(4, '0'); // '0009'
n = 10;
String(n).padStart(4, '0'); // '0010'
Not a lot of "slick" going on so far:
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
When you initialize an array with a number, it creates an array with the length set to that value so that the array appears to contain that many undefined elements. Though some Array instance methods skip array elements without values, .join() doesn't, or at least not completely; it treats them as if their value is the empty string. Thus you get a copy of the zero character (or whatever "z" is) between each of the array elements; that's why there's a + 1 in there.
Example usage:
pad(10, 4); // 0010
pad(9, 4); // 0009
pad(123, 4); // 0123
pad(10, 4, '-'); // --10
function padToFour(number) {
if (number<=9999) { number = ("000"+number).slice(-4); }
return number;
}
Something like that?
Bonus incomprehensible-but-slicker single-line ES6 version:
let padToFour = number => number <= 9999 ? `000${number}`.slice(-4) : number;
ES6isms:
let is a block-scoped variable (as opposed to var’s functional scoping)
=> is an arrow function that, among other things, replaces function and is prepended by its parameters
If an arrow function takes a single parameter, you can omit the parentheses (hence number =>)
If an arrow function body has a single line that starts with return, you can omit the braces and the return keyword and simply use the expression
To get the function body down to a single line, I cheated and used a ternary expression
Try:
String.prototype.lpad = function(padString, length) {
var str = this;
while (str.length < length)
str = padString + str;
return str;
}
Now test:
var str = "5";
alert(str.lpad("0", 4)); //result "0005"
var str = "10"; // note this is string type
alert(str.lpad("0", 4)); //result "0010"
DEMO
In ECMAScript 2017 , we have new method padStart and padEnd which has below syntax.
"string".padStart(targetLength [,padString]):
So now we can use
const str = "5";
str.padStart(4, "0"); // "0005"
Funny, I recently had to do this.
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
Use like:
padDigits(9, 4); // "0009"
padDigits(10, 4); // "0010"
padDigits(15000, 4); // "15000"
Not beautiful, but effective.
You did say you had a number-
String.prototype.padZero= function(len, c){
var s= '', c= c || '0', len= (len || 2)-this.length;
while(s.length<len) s+= c;
return s+this;
}
Number.prototype.padZero= function(len, c){
return String(this).padZero(len,c);
}
You could do something like this:
function pad ( num, size ) {
return ( Math.pow( 10, size ) + ~~num ).toString().substring( 1 );
}
Edit: This was just a basic idea for a function, but to add support for larger numbers (as well as invalid input), this would probably be better:
function pad ( num, size ) {
if (num.toString().length >= size) return num;
return ( Math.pow( 10, size ) + Math.floor(num) ).toString().substring( 1 );
}
This does 2 things:
If the number is larger than the specified size, it will simply return the number.
Using Math.floor(num) in place of ~~num will support larger numbers.
This is not really 'slick' but it's faster to do integer operations than to do string concatenations for each padding 0.
function ZeroPadNumber ( nValue )
{
if ( nValue < 10 )
{
return ( '000' + nValue.toString () );
}
else if ( nValue < 100 )
{
return ( '00' + nValue.toString () );
}
else if ( nValue < 1000 )
{
return ( '0' + nValue.toString () );
}
else
{
return ( nValue );
}
}
This function is also hardcoded to your particular need (4 digit padding), so it's not generic.
For fun, instead of using a loop to create the extra zeros:
function zeroPad(n,length){
var s=n+"",needed=length-s.length;
if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
return s;
}
Since you mentioned it's always going to have a length of 4, I won't be doing any error checking to make this slick. ;)
function pad(input) {
var BASE = "0000";
return input ? BASE.substr(0, 4 - Math.ceil(input / 10)) + input : BASE;
}
Idea: Simply replace '0000' with number provided... Issue with that is, if input is 0, I need to hard-code it to return '0000'. LOL.
This should be slick enough.
JSFiddler: http://jsfiddle.net/Up5Cr/

Categories

Resources