Truncate a number - javascript

function truncDigits(inputNumber, digits) {
const fact = 10 ** digits;
return Math.trunc(inputNumber * fact) / fact;
}
truncDigits(27624.399999999998,2) //27624.4 but I want 27624.39
I need to truncate a float value but don't wanna round it off. For example
27624.399999999998 // 27624.39 expected result
Also Math.trunc gives the integer part right but when you Math.trunc value 2762439.99 it does not give the integer part but gives the round off value i.e 2762434

Probably a naive way to do it:
function truncDigits(inputNumber, digits) {
return +inputNumber.toString().split('.').map((v,i) => i ? v.slice(0, digits) : v).join('.');
}
console.log(truncDigits(27624.399999999998,2))
At least it does what you asked though

Try this:
function truncDigits(inputNumber, digits){
return parseFloat((inputNumber).toFixed(digits));
}
truncDigits(27624.399999999998,2)
Your inputs are number (if you are using typescript). The method toFixed(n) truncates your number in a maximum of n digits after the decimal point and returns it as a string. Then you convert this with parseFloat and you have your number.

You can try to convert to a string and then use a RegExp to extract the required decimals
function truncDigits(inputNumber: number, digits: number) {
const match = inputNumber.toString().match(new RegExp(`^\\d+\\.[\\d]{0,${digits}}`))
if (!match) {
return inputNumber
}
return parseFloat(match[0])
}
Note: I'm using the string version of the RegExp ctor as the literal one doesn't allow for dynamic params.

Related

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));

In Javascript what is the method to allow integer and float but not chars

In my javascript variable I am getting the value as "abc" or "123" or "123.456" based on the input given in the input field. For all the values the type is string even if the entered value is number or float.
typeof(variable) gives string always.
The following method will be triggered on each keydown. I am also using the lodash library
convertMethod(val) {
console.log(round(val,2).toString()) //round is a lodash method which is imported already
}
When I round the value the decimal point is not coming. I just want to round the value by two decimal points if the entered value is digits and not alphabets. How can I fix this?
You can check if it number or not using isNaN. Round it up if it is a number:
convertMethod(val) {
if(!isNaN(val))
console.log(round(val,2).toString())
else
console.log(val)
}
convertMethod("qw")
convertMethod("12.3456")
convertMethod("12.432")
convertMethod("12")
Output:
"qw"
"12.35"
"12.43"
"12"
Try converting the string to a number (via _.toNumber() or the + operator. Then check if it's a number using _.isFinite() which returns false for non numbers, Infinite, -Infinite, and NaN.
const { isFinite, round } = _
const convertMethod = val => {
if (isFinite(+val))
console.log(round(val, 2).toString())
else
console.log(val)
}
convertMethod('5.4435')
convertMethod('abc')
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Counting numbers after decimal point in JavaScript

I have a problem in JavaScript. Is it possible to check how many numbers are after the decimal point? I tried to do it using a.toString().split(".")[1]), but if there is no decimal point in the number, there is an error. What should I do if I want the system to do nothing if there is no decimal point?
You're on the right track. You can also .includes('.') to test if it contains a decimal along with .length to return the length of the decimal portion.
function decimalCount (number) {
// Convert to String
const numberAsString = number.toString();
// String Contains Decimal
if (numberAsString.includes('.')) {
return numberAsString.split('.')[1].length;
}
// String Does Not Contain Decimal
return 0;
}
console.log(decimalCount(1.123456789)) // 9
console.log(decimalCount(123456789)) // 0
Convert to a string, split on “.”, then when there is no “.” to split on, assume it’s empty string '' (the part you’re missing), then get said string’s length:
function numDigitsAfterDecimal(x) {
var afterDecimalStr = x.toString().split('.')[1] || ''
return afterDecimalStr.length
}
console.log(numDigitsAfterDecimal(1.23456))
console.log(numDigitsAfterDecimal(0))
You could check if no dot is available, then return zero, otherwise return the delta of the lenght and index with an adjustment.
function getDigits(v) {
var s = v.toString(),
i = s.indexOf('.') + 1;
return i && s.length - i;
}
console.log(getDigits(0));
console.log(getDigits(0.002));
console.log(getDigits(7.654321));
console.log(getDigits(1234567890.654321));
The condition you need is:
number.split('.')[1].length
It checks if there are any numbers after the dot which separates the number from its decimal part.
I'm not sure if you are able to use split on numbers though. If not, parse it to a string.
You first need to convert the decimal number to string and then get the count of character after decimal point,
var a = 10.4578;
var str = a.toString();
if(str){
var val = str.split('.');
if(val && val.length == 2){
alert('Length of number after decimal point is ', val[1].length);
} else {
alert('Not a decimal number');
}
}
The output is 4

parse integer with javascript using parseInt and a radix

I am doing an online test and it asks me to write basic javascript code.
It asks me to parse a numberic string and convert it to a number of a different base. It needs me to return -1 if for whatever reason the conversion cannot be done.
I have written this:
function convert(strNumber, radix) {
var result = parseInt(strNumber, radix);
if(isNaN(result))
{return -1;}
return result;
}
Then it runs my code through various tests and all pass. Except one.
Apparently convert("ASD", 15) should be invalid according to the test and it expects it to be -1.
But Javascript happily converts it to number 10
I tried various things such as to add a try{}catch{} block and other things, but javascript never complains about converting "ASD" to base 15.
Is the test wrong, or is parseInt wrong?
By the way strNumber can be any base under 36.
So for instance:
convert("Z", 36) is 35
As I stated in the comment, parseInt will convert up to the point where it fails. So "A" is valid in that radix and "S" is not. So you would need to add a check.
var nums = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".substr(0, radix)
var re = new RegExp("^[" + nums + "]+$","i")
if (!re.test(strNumber)) {
return -1
}
parseInt is behaving normally and is converting the letter A into 10 in base 15 (similar to how hex uses A for the number 10). The S and D are discarded, as parseInt accepts this type of malformed input.
From the parseInt documentation:
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.
As per official documentation the parseInt function behaves as following
For radices above 10, the letters of the alphabet indicate numerals
greater than 9. For example, for hexadecimal numbers (base 16), A
through F are used.
and
If parseInt encounters a character that is not a numeral in the
specified radix, it ignores it and all succeeding characters and
returns the integer value parsed up to that point.
Thus to prevent invalid arguments from being parsed they have to be validated first
function convert(strNumber, radix) {
if (isValidRadix(radix) && isValidInteger(strNumber, radix))
return parseInt(strNumber, radix);
return -1;
}
function isValidInteger(str, radix) {
var letters = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'].slice(0,radix);
str = str.toUpperCase();
for (var i=0; i<str.length; i++) {
var s = str.charAt(i);
if (letters.indexOf(s) == -1) return false;
}
return true;
}
function isValidRadix(radix) {
// 16 up to HEX system
return radix > 0 && radix <= 16;
}
console.log(convert("ASD", 15));
console.log(parseInt("ASD", 15));
console.log(convert("AAA", 15));

value more than not read in if condition in javascript

I m getting two textboxes value as 5 and 10.
so i m validating them on the following if condition
var textboxvalue1 = $('#textboxvalue1' + counter).val();
var textboxvalue2 = $('#textboxvalue2' + counter).val();
if (textboxvalue1 < textboxvalue2) {
alert("error");
}
textboxvalue1 = 10
textboxvalue2 = 5
its showing an alert in this case.which it shud nt show.bt when textboxvalue1 is less than 10,it works fine.
Actually your .val() returns string you try to convert it as integer so use parseInt() in your context and check.
The parseInt() function parses a string and returns an integer.
Note:
The radix parameter is used to specify which numeral system to be
used, for example, a radix of 16 (hexadecimal) indicates that the
number in the string should be parsed from a hexadecimal number to a
decimal number.
If the radix parameter is omitted, 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)
var textboxvalue1= parseInt($('#textboxvalue1'+counter).val(), 10);
var textboxvalue2= parseInt($('#textboxvalue2'+counter).val(), 10);
if (textboxvalue1 < textboxvalue2) {
alert("error");
}
You have to convert your input strings to numbers like this:
var textboxvalue1=parseInt($('#textboxvalue1'+counter).val());
var textboxvalue2=parseInt($('#textboxvalue2'+counter).val());
The values are being interpreted as strings by JavaScript, not numbers. Wrap them in parseInt or parseFloat before comparing them.
Use ParseInt Because var return string default. Or you can use parseFloat
var textboxvalue1= parseInt($('#textboxvalue1'+counter).val(), 10);
var textboxvalue2= parseInt($('#textboxvalue2'+counter).val(), 10);
if (textboxvalue1 < textboxvalue2) {
alert("error");
}

Categories

Resources