const id = 46919;
const string = id.toString(36); // output: "107b"
console.log(string.padStart(3, '0'));
The expected output of the console.log() would be 107 since the targetLength of method padStart() is equal to 3, but the actual output is 107b which is a total of 4 characters.
Would you know why this happens please?
Edit: I misunderstood the use of this method, I thought it would cut the extra characters like slice()
Maybe you can use parseInt() in the end of code
const id = 46919;
const string = id.toString(36);
console.log(parseInt(string.padStart(3, '0')));
//output 107
the toString(36) converts the number to base 36 from base 10, 46919 is 107b in base 36. padStart will add characters until the length is equal to the first parameter. Since 107b is already 4 characters it doesn't do anything.
Related
I know about decimalPlaces:
const number = new BigNumber(100.5254);
number.decimalPlaces(); // 4
And precision:
const number = new BigNumber(100.5254);
number.precision(); // 7
But I couldn't find any function that returns only the number of characteristics. That is, in this example, 3 ("1", "0" and "0").
Is there something for this?
It seems there isn't one, as of Nov 2019 at least, but you can subtract the decimal places from the total precision to get the digits before the dot:
const number = new BigNumber(100.5254);
const digitsBeforeDot = number.precision(true) - number.decimalPlaces();
// prints 3
Note that:
If d (the first parameter of the precision function) is true then any trailing zeros of the integer part of a number are counted as significant digits, otherwise they are not.
See the docs:
decimalPlaces()
precision()
In the same way we have the hex "number" using the characters 123456789abcdef, and you can simply do integer.toString(16) to go from integer to hex:
> (16).toString(16)
'10'
... I would like to instead use a custom character set, and a custom base. So for hex say I wanted to use the characters 13579acegikmoqsu, then it would be something like this:
> (16).toString(16, '13579acegikmoqsu')
'ik'
I don't actually know what the output value would be in this case, just made that up. But I am looking for how to do this in JavaScript.
Another example outside of hex would be a, for example, base 6 number converted to a string using the character set and123, so it would be something like this:
> (16).toString(6, 'and123')
'a3d'
I don't know what the value is in this case here either, I don't know how to calculate it. Basically wondering how to do this in JavaScript, not necessarily using this toString api, preferably it would be a bit more low-level so I could also understand the logic behind it.
Likewise, it would be helpful to know how to reverse it, so to go from a3d => 16 as in this pseudo-example.
You could map the character values of the integer value as index
function toString(n, characters) {
var radix = characters.length;
return Array
.from(n.toString(radix), v => characters[parseInt(v, radix)])
.join('');
}
console.log(toString(16, '13579acegikmoqsu')); // 31
A version without toString and parseInt.
function toString(n, characters) {
var radix = characters.length,
temp = [];
do {
temp.unshift(n % radix);
n = Math.floor(n / radix);
} while (n)
return temp
.map(i => characters[i])
.join('');
}
console.log(toString(16, '13579acegikmoqsu')); // 31
What is the proper way to add the sum of multiple variables in Javascript?
This is what I'm trying to do. I've tried it with and without the quotes around my variables. I'm not getting a NaN or an Undefined or anything. No output whatsoever.
function setstat(){
document.getElementById('date').value = window.opener.document.getElementById('thisday').value;
document.getElementById('name').value = window.opener.document.getElementById('element_7').value;
document.getElementById('time').value = window.opener.document.getElementById('stwa').value;
inbcalls = window.opener.document.getElementById('element_6').value;
document.getElementById('totinb').value = inbcalls;
inbcallsp = parseInt("inbcalls",10);
asaptotal = window.opener.document.getElementById('asapcalls').value;
document.getElementById('asaptot').value = asaptotal;
asaptotalp = parseInt("asaptotal",10);
faxtotal = window.opener.document.getElementById('faxcalls').value;
document.getElementById('faxtot').value = faxtotal;
faxtotalp = parseInt("faxtotal",10);
obtotal = window.opener.document.getElementById('obcalls').value;
document.getElementById('obtot').value = obtotal;
totalcalls = inboundcallsp + asaptotalp + faxtotalp + obtotalp;
document.getElementById('totsum').value = totalcalls;
}
Why are you quoting the variable names?
inbcallsp = parseInt("inbcalls",10);
should be:
inbcallsp = parseInt(inbcalls, 10);
And the same for the rest of them. You want to parse the value of the variables, not the names of the variables; those will always result in NaN.
asaptotalp = parseInt("asaptotal",10);
"asaptotal" is recognize as the string not the variable
you should not quote it
When using parseInt always specify the radix as 10.
The function singnature: parseInt(string, radix)
The radix is optional but if ommited, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)
Example:
parseIn("05") ==== 0 -> true
parseIn("05", 10) ==== 5 -> true
Don't use ParseInt, sometimes it will not return the proper value.
Better use Number, for example:
var i=Number(your value)
Trying to calculate sum of checked tr's.
var totalqt=0;
totalqt=totalqt + $(this).closest("tr").find("#qt").text();
It gets correct values but doesn't operate with it like digits. for ex, if value was 1 for first td, and 2 for second td, it alerts 12 instead of 1+2. Tried text() and html(). Same result. What's wrong?
totalqt = totalqt + parseInt($(this).closest("tr").find("#qt").text(), 10);
You need to parse the value as a number this will either be using parseInt(val, base) or parseFloat(val, base):
In your example you'd use:
var totalqt=0;
totalqt=totalqt +parseInt( $(this).closest("tr").find("#qt").text(), 10);
You need to parse the string to an int so that you can use it like an int.
var totalqt=0;
totalqt=totalqt + parseInt($(this).closest("tr").find("#qt").text(), 10);
The 10 is because:
The problem is with how parseInt guesses the base of your number. Read
the parseInt spec. Instead of always defaulting to base 10, it tries
to guess, and if the first character is '0' it thinks you want to
parse as an octal number, and if it starts with '0x' it thinks you
want hexadecimal.
text() returns a string. You want a number. Use parseInt:
var totalqt = 0;
totalqt = totalqt + parseInt($(this).closest("tr").find("#qt").text(), 10);
I wanted to display a number to 2 decimal places.
I thought I could use toPrecision(2) in JavaScript .
However, if the number is 0.05, I get 0.0500. I'd rather it stay the same.
See it on JSbin.
What is the best way to do this?
I can think of coding a few solutions, but I'd imagine (I hope) something like this is built in?
float_num.toFixed(2);
Note:toFixed() will round or pad with zeros if necessary to meet the specified length.
You could do it with the toFixed function, but it's buggy in IE. If you want a reliable solution, look at my answer here.
number.parseFloat(2) works but it returns a string.
If you'd like to preserve it as a number type you can use:
Math.round(number * 100) / 100
Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:
var num = response_from_a_function_or_something();
var fixedNum = parseFloat(num).toFixed( 2 );
with toFixed you can set length of decimal points like this:
let number = 6.1234
number.toFixed(2) // '6.12'
but toFixed returns a string and also if number doesn't have decimal point at all it will add redundant zeros.
let number = 6
number.toFixed(2) // '6.00'
to avoid this you have to convert the result to a number. you can do this with these two methods:
let number1 = 6
let number2 = 6.1234
// method 1
parseFloat(number1.toFixed(2)) // 6
parseFloat(number2.toFixed(2)) // 6.12
// method 2
+number1.toFixed(2) // 6
+number2.toFixed(2) // 6.12
Try toFixed instead of toPrecision.
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // return 1.01
round(1.004, 2); // return 1 instead of 1.00
The answer is following this link: http://www.jacklmoore.com/notes/rounding-in-javascript/
I used this way if you need 2 digits and not string type.
const exFloat = 3.14159265359;
console.log(parseFloat(exFloat.toFixed(2)));
You could try mixing Number() and toFixed().
Have your target number converted to a nice string with X digits then convert the formated string to a number.
Number( (myVar).toFixed(2) )
See example below:
var myNumber = 5.01;
var multiplier = 5;
$('#actionButton').on('click', function() {
$('#message').text( myNumber * multiplier );
});
$('#actionButton2').on('click', function() {
$('#message').text( Number( (myNumber * multiplier).toFixed(2) ) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button id="actionButton">Weird numbers</button>
<button id="actionButton2">Nice numbers</button>
<div id="message"></div>
The toFixed() method formats a number using fixed-point notation.
and here is the syntax
numObj.toFixed([digits])
digits argument is optional and by default is 0. And the return type is string not number. But you can convert it to number using
numObj.toFixed([digits]) * 1
It also can throws exceptions like TypeError, RangeError
Here is the full detail and compatibility in the browser.
let a = 0.0500
a.toFixed(2);
//output
0.05
There's also the Intl API to format decimals according to your locale value. This is important specially if the decimal separator isn't a dot "." but a comma "," instead, like it is the case in Germany.
Intl.NumberFormat('de-DE').formatToParts(0.05).reduce((acc, {value}) => acc += value, '');
Note that this will round to a maximum of 3 decimal places, just like the round() function suggested above in the default case. If you want to customize that behavior to specify the number of decimal places, there're options for minimum and maximum fraction digits:
Intl.NumberFormat('de-DE', {minimumFractionDigits: 3}).formatToParts(0.05)
float_num = parseFloat(float_num.toFixed(2))
I have made this function. It works fine but returns string.
function show_float_val(val,upto = 2){
var val = parseFloat(val);
return val.toFixed(upto);
}