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.
Related
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.
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.
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
I have this line of javascript in an event handler:
var value = event.currentTarget.value; //example: 9
which I then use in a switch statement.
switch (value) {
case 9:
return 12;
case 12:
return 9;
}
The problem is that "value" is a string instead of an int.
Should I just cast this to an int?
Or is there a way to get the value as an int, like say with jQuery()?
Or should I just use strings in the switch statement?
Or is there a way to get the value as an int, like say with jQuery()?
Of course, this is almost always a feature provided in a language or environment. In JavaScript, there are four ways:
parseInt will parse the string as a whole number. value = parseInt(value, 10) will parse it as decimal (e.g., base 10, the number system most of us use). Note that parseInt will parse the number it finds at the beginning of the string, ignoring anything after it. So parseInt("1blah", 10) is 1.
parseFloat will parse the string as a potentially-fractional number (like 1.2), if the string contains a decimal point. It always works in base 10.
The Number function: value = Number(value). That expects the entire string to be a number, and figures out what number base it is by looking at the string: The default is decimal, but if it starts with 0x it's parsed as hexadecimal (base 16), and on some engines in loose mode if it starts with 0 it's parsed as octal (base 8). There's no way to force it to use a particular number base.
Force the engine to implicitly convert it by applying a math operator to it; the usual one is +. So: value = +value. That does the same thing value = Number(value) does. Oddly, it tends to be slower than Number on some engines, but not enough to matter.
Examples:
parseInt("15", 10): 15
parseFloat("15"): 15
Number("15"): 15
+"15": 15
parseInt("1.4", 10): 1
parseFloat("1.4"): 1.4
Number("1.4"): 1.4
+"1.4": 1.4
parseInt("10 nifty things", 10): 10
parseFloat("10 nifty things"): 10
Number("10 nifty things"): NaN
+"10 nifty things": NaN
Live Copy:
console.log(parseInt("15", 10)); // 15
console.log(parseFloat("15")); // 15
console.log(Number("15")); // 15
console.log(+"15"); // 15
console.log(parseInt("1.4", 10)); // 1
console.log(parseFloat("1.4")); // 1.4
console.log(Number("1.4")); // 1.4
console.log(+"1.4"); // 1.4
console.log(parseInt("10 nifty things", 10)); // 10
console.log(parseFloat("10 nifty things")); // 10
console.log(Number("10 nifty things")); // NaN
console.log(+"10 nifty things"); // NaN
.as-console-wrapper {
max-height: 100% !important;
}
Simple use +value, Notice + in front of a variable with converts the variable to a number
switch (+value) {
case 9:
return 12;
case 12:
return 9;
}
Try this one. parseInt() function does parse a string and returns an integer.
var value = parseInt(event.currentTarget.value, 10);
How can you find the whole number of a given decimal or other number in JavaScript?
Given Result
----- ------
1.2 1
1.5 1
1.9 1
What's the best way to perform this for both positive and negative numbers?
Using Math.floor:
Math.floor(number)
You can also use newNumber = parseInt(number, 10);
With ES6, there is Math.trunc(), this function returns the integer part of a number by removing any fractional digits.
This differs from the Math.floor() while handling the negative numbers.
console.log(Math.trunc(3.14)); // 3
console.log(Math.trunc(-3.14)); // -3
console.log(Math.floor(-3.14)); // Here floor gives -4.
So essentially you can get rid of writing this longer expression
number > 0 ? Math.floor(number) : Math.ceil(number)
Bitwise operators - the shortest syntax for positive numbers having integral part of number <= 2^31-1
~~1.2 // 1
~~1.5 // 1
~~1.9 // 1
1.2>>0 // 1
1.5>>0 // 1
1.9>>0 // 1
1.2|0 // 1
1.5|0 // 1
1.9|0 // 1
With values exceeding 2^31-1 will return incorrect results.
for negative numbers you can just use Math.abs(num) and it will knock off the - sign from the start