how do i convert number starting with decimal to zero - javascript

I need to convert number starting with decimal like .15 to 0 rather then 0.15 in javascript.
using ParseInt(value) only work for leading zero numbers like 001 or 0.1.
can anyone provide me good solution ??

An input value is a String! Trying to use parseInt on a non-number (string decimal missing integer) will result in NaN when the parser tries to perform a string-to-number conversion:
parseInt(".15", 10) // NaN
In that case you need to first convert it to a Number:
parseInt(Number(".15"), 10) // 0
(or using the Unary +)
parseInt( +".15", 10) // 0

Related

remove leading 0 before decimal point and return as a number- javascript

Problem
I need to return a number in the format of .66 (from an entered value which includes the leading zero, e.g. 0.66)
It must be returned as an integer with the decimal point as the first character.
what method in JavaScript can help me do this?
What have I tried?
I've tried converting it toString() and back to parseInt() but including the decimal point makes it return NaN.
I've tried adding various radix (10, 16) to my parseInt() - also unsuccessful
Sample Code
const value = 0.66;
if(value < 1) {
let str = value.toString().replace(/^0+/, '');
// correctly gets '.66'
return parseInt(str)
}
//result NaN
Expectations
I expect an output of the value with the leading 0 removed
e.g. 0.45 --> .45 or 0.879 --> .879
Current Observations
Output is NaN
I tried a quick solution, you may try to do this:
let a = 0.45;
// split on decimal, at index 1 you will find the number after decimal
let b = a.toString().split('.')[1];
Issue #1:
0.66 is not an Integer. An Integer is a whole number, this is a floating-point number.
Issue #2:
You cannot have a number in JavaScript that starts with a decimal point.
Even if you change your parseInt to be parseFloat, it will still return 0.66 as a result.
What you're asking just isn't possible, if you want a number to start with a decimal point then it has to be a string.

How do I round to 1 decimal on the bbc:microbit with javascript w/o toFixed(), the usual multiplication + divide gives trailing 9999 digits?

temperatureReading = Math.round(temperatureReading * 10) / 10
gives me 26.29999999999999999999 instead of 26.3
And 26.00000000001 instead of 26.0
I get alternating 2 values from the temperature sensor: 26.33 and 26.3200000
After the conversion I have: 26.2999999999999
The number of the repeating digits above is just an example. My display on the micro bit is not wide enough to see them all.
I use toString() to display the values.
Unfortunately, toFixed() and toPrecision() is not available on the micro:bit
Can the rounding be achieved by some other operations?
With the following code I can now get numbers with 1 decimal as a string:
let temperatureStr = Math.round(temperatureReading * 10).toString()
let temperature = temperatureStr.slice(0, temperatureStr.length - 1) + "." + temperatureStr.slice(temperatureStr.length - 1);
I first multiply the number by 10 and convert the result to a string. Then, I insert the decimal point before the last digit. This gives me the string I want to print.

Numeric conversion in JavaScript [duplicate]

How do parseInt() and Number() behave differently when converting strings to numbers?
Well, they are semantically different, the Number constructor called as a function performs type conversion and parseInt performs parsing, e.g.:
// parsing:
parseInt("20px"); // 20
parseInt("10100", 2); // 20
parseInt("2e1"); // 2
// type conversion
Number("20px"); // NaN
Number("2e1"); // 20, exponential notation
Also parseInt will ignore trailing characters that don't correspond with any digit of the currently used base.
The Number constructor doesn't detect implicit octals, but can detect the explicit octal notation:
Number("010"); // 10
Number("0o10") // 8, explicit octal
parseInt("010"); // 8, implicit octal
parseInt("010", 10); // 10, decimal radix used
And it can handle numbers in hexadecimal notation, just like parseInt:
Number("0xF"); // 15
parseInt("0xF"); //15
In addition, a widely used construct to perform Numeric type conversion, is the Unary + Operator (p. 72), it is equivalent to using the Number constructor as a function:
+"2e1"; // 20
+"0xF"; // 15
+"010"; // 10
typeof parseInt("123") => number
typeof Number("123") => number
typeof new Number("123") => object (Number primitive wrapper object)
first two will give you better performance as it returns a primitive instead of an object.
One minor difference is what they convert of undefined or null,
Number() Or Number(null) Or Number('') // returns 0
while
parseInt() Or parseInt(null) // returns NaN
Summary:
parseInt():
Takes a string as a first argument, the radix (An integer which is the base of a numeral system e.g. decimal 10 or binary 2) as a second argument
The function returns a integer number, if the first character cannot be converted to a number NaN will be returned.
If the parseInt() function encounters a non numerical value, it will cut off the rest of input string and only parse the part until the non numerical value.
If the radix is undefined or 0, JS will assume the following:
If the input string begins with "0x" or "0X", the radix is 16 (hexadecimal), the remainder of the string is parsed into a number.
If the input value begins with a 0 the radix can be either 8 (octal) or 10 (decimal). Which radix is chosen is depending on JS engine implementation. ES5 specifies that 10 should be used then. However, this is not supported by all browsers, therefore always specify radix if your numbers can begin with a 0.
If the input value begins with any number, the radix will be 10
Number():
The Number() constructor can convert any argument input into a number. If the Number() constructor cannot convert the input into a number, NaN will be returned.
The Number() constructor can also handle hexadecimal number, they have to start with 0x.
Example:
console.log(parseInt('0xF', 16)); // 15
// z is no number, it will only evaluate 0xF, therefore 15 is logged
console.log(parseInt('0xFz123', 16));
// because the radix is 10, A is considered a letter not a number (like in Hexadecimal)
// Therefore, A will be cut off the string and 10 is logged
console.log(parseInt('10A', 10)); // 10
// first character isnot a number, therefore parseInt will return NaN
console.log(parseInt('a1213', 10));
console.log('\n');
// start with 0X, therefore Number will interpret it as a hexadecimal value
console.log(Number('0x11'));
// Cannot be converted to a number, NaN will be returned, notice that
// the number constructor will not cut off a non number part like parseInt does
console.log(Number('123A'));
// scientific notation is allowed
console.log(Number('152e-1')); // 15.21
If you are looking for performance then probably best results you'll get with bitwise right shift "10">>0. Also multiply ("10" * 1) or not not (~~"10"). All of them are much faster of Number and parseInt.
They even have "feature" returning 0 for not number argument.
Here are Performance tests.
I found two links of performance compare among several ways of converting string to int.
parseInt(str,10)
parseFloat(str)
str << 0
+str
str*1
str-0
Number(str)
http://jsben.ch/#/zGJHM
http://phrogz.net/js/string_to_number.html
parseInt() -> Parses a number to specified redix.
Number()-> Converts the specified value to its numeric equivalent or NaN if it fails to do so.
Hence for converting some non-numeric value to number we should always use Number() function.
eg.
Number("")//0
parseInt("")//NaN
Number("123")//123
parseInt("123")//123
Number("123ac") //NaN,as it is a non numeric string
parsInt("123ac") //123,it parse decimal number outof string
Number(true)//1
parseInt(true) //NaN
There are various corner case to parseInt() functions as it does redix conversion, hence we should avoid using parseInt() function for coersion purposes.
Now, to check weather the provided value is Numeric or not,we should use nativeisNaN() function
I always use parseInt, but beware of leading zeroes that will force it into octal mode.
It's a good idea to stay away from parseInt and use Number and Math.round unless you need hex or octal. Both can use strings. Why stay away from it?
parseInt(0.001, 10)
0
parseInt(-0.0000000001, 10)
-1
parseInt(0.0000000001, 10)
1
parseInt(4000000000000000000000, 10)
4
It completely butchers really large or really small numbers. Oddly enough it works normally if these inputs are a string.
parseInt("-0.0000000001", 10)
0
parseInt("0.0000000001", 10)
0
parseInt("4000000000000000000000", 10)
4e+21
Instead of risking hard to find bugs with this and the other gotchas people mentioned, I would just avoid parseInt unless you need to parse something other than base 10. Number, Math.round, Math.floor, and .toFixed(0) can all do the same things parseInt can be used for without having these types of bugs.
If you really want or need to use parseInt for some of it's other qualities, never use it to convert floats to ints.
parseInt converts to a integer number, that is, it strips decimals. Number does not convert to integer.
Another way to get the result is to use the ~ operator
For most circumstances
~~someThing === parseInt(something)
but ~~ will return zero for strings that parseInt will accept with trailing other characters or with the number base spec (eg hex) and will also return zero when parseInt returns NaN. Another difference is that ~~ if given a bigint returns a bigint to which you can add another bigint whereas parseInt returns an ordinary floating point number (yes really - it gives exactly the same value as parseFloat) if the bigint is large
However for most circumstances ~~ is 30% faster than parseInt. It is only slower by 10% when something is a floating point represented as a string.
So if the more restricted scope of ~~ fits your need then save the computer time and give yourself less to type

Convert 0 to 0.00 as number

I am trying to convert numbers in following formats
0 -> 0.00
1 -> 1.00
1.1 -> 1.10
4.0 -> 4.00
But problem is its returning as string only
value = 0;
var s = Math.floor(value / 60) + "." + (value % 60 ? value % 60 : '00');
console.log(s+s); //just checking if its number
But its returning as string , I tried parseInt , but its returning only 0 . I tried ParseFloat and fixedTo(2) , its returning as string only.
As seen in the comments, there is no way for that in JavaScript. Formatting a Number always returns a Srting. For this you have some possibilities, though
Number(1).toFixed(2) // "1.00" - setting the number of digits after the decimal point
Number(1).toPrecision(2) // "1.0" - setting the number of digits
These are for printing it out, so normally, it shouldn't matter if it is a String or a Number.
Then if you want to use it as a Number, you just follow #Max 's advice and convert it using the function Number(str) or the shorthand +str.

Does the number -0 exists in Javascript?

I was doing some money calculation and I got the number -0. This number -0 does not exists, since 0 does not have a sign. Why is this happening? I know the original price has more digits on my bd. but anyway this behaviour thing is weird anyway.
So I'm using this math expression: I pick the item price and subtract the discount, then I round it up.
(19.99923-20).toFixed(2)
And I get "-0.00" !? this is ugly to display. I tried using the Number() to make it a "real number", but
Number((19.99923-20).toFixed(1))
will appear as "-0".
What's wrong with javascript, there is no number -0, it should be just "0"?
JavaScript keeps sign with floating negatives close to 0, either using Math.round() or toFixed(), both can get you a -0. Solved that applying a quick fix, which consists in checking if our number enters that range in between 0 and -0.005 (rounded to -0.01 later). Considered 2 floating digits as your example works with money, so I considered a difference of 1 cent relevant:
var num=19.99923-20;
if(num>-0.005 && num<0){
num=0; //we set to '0' all -0
}else{
num=num*100;
num=Math.round(num);
num=num/100;
/*or
num=num.toFixed(2);
but this way we convert number to string*/
}
Hope it helps.
toFixed converts a number to string, not a number. So the -0.00 you are seeing is a string. Its the result of converting
19.99923-20 // which is about
-0.0007699999999992713 // in internal representation
to a string using the toFixed method in ECMAscript standards, which initialises the result to "-" for negative numbers and proceeds to convert the absolute (positive) value of the number being converted.
Converting the string "-0.00" back to a number with either parseFloat("-0.00") or Number("-0.00") returns a positive zero number representation (javscript stores numbers using the IEEE 754 standard for double precision float representation, which does have a negative zero value, but it's not the problem here.)
Looking at how toFixed works suggests the only problem is with a "-0.00" result, which can be checked using string comparison:
var number = 19.99923-20;
var str = number.toFixed(2);
if( str == "-0.00")
str = "0.00";
Alternatively you could consider using a conversion routine which never returns a negatively signed zero string such as:
function convertFixed( number, digits) {
if(isNaN(number))
return "NaN";
var neg = number < 0;
if( neg)
number = -number;
var string = number.toFixed(digits);
if( neg && Number(string) === 0) // negative zero result
neg = false;
return neg ? "-" + string : string;
}

Categories

Resources