I have a number with a comma, for example: 254,5. I need the 0 behind the ,5 so it stands like 254,50 instead..
I'm using this to get the number:
Math.floor(iAlt / 50) * 50;
How can i get the 0 behind the ,5?
Try the toFixed() method, which pads the decimal value to length n with 0's.
var result = (Math.floor(iAlt / 50) * 50).toFixed(2);
A Number will always remove trailing zeros, so toFixed returns a String.
It's important to note that toFixed must be called on a number. Call parseFloat() or parseInt() to convert a string to a number first, if required (not in this situation, but for future reference).
Related
I'm new to writing JavaScript, I'm trying to convert two values from a string to a number, however, I have tried to doing the following approaches but none seem to work.
Example:
const num = parseInt('100.00') // returns 100
const num = Number('100.00') // returns 100
const num = +'100.00'; // returns 100
I need to return 100.00 as a number I have gone to other similar post they didn't seem to help, all knowledge is appreciated thanks!
In Javascript everything is Number, which is double-precision floating point 64 bit number (=decimal).
100.00 is equal to 100, therefore it shows you 100.
What you are asking is not possible, the decimal 100 is not representable as 100.00 as number, you can only represent it as a String with help of toFixed;
var num = 100;
var strNum = num.toFixed(2); // in this case you have a string instead of a number
console.log(typeof num, num);
console.log(typeof strNum, strNum);
It seems to me that all the approaches you have tried work.
Internally, JavaScript stores all numbers using the floating point format. It uses the minimum number of decimals needed when it displays the value.
This is 0 for integer numbers as 100. 100.00 is still 100, adding any number of 0 after the decimal point doesn't change its value.
The recommended method to parse a string that looks like a number is to use Number.parseInt() or Number.parseFloat().
parseFloat() recognizes only numbers written in base 10 but parseInt() attempts to detect the base by analyzing the first characters of the input string. It automatically recognizes numbers written in bases 2, 8, 10 and 16 using the rules described in the documentation page about numbers. This is why it's recommended to always pass the second argument to parseInt() to avoid any ambiguity.
Regarding your concern, use Number.toFixed() to force its representation using a certain number of decimal digits, even when the trailing digits are 0:
const num = parseInt('100.00');
console.log(num); // prints '100'
console.log(num.toFixed(2)); // prints '100.00'
I have already tried the following:
discval = 2.833423
discval = discval.toFixed(2).toString().replace("." , ",");
discval = parseFloat(discval);
The output is 2 and not 2,83
Any idea?
parseFloat("2,83") will return 2 because , is not recognized as decimal separator, while . is.
If you want to round the number to 2 decimal places just use parseFloat(discval.toFixed(2)) or Math.round(discval * 100) / 100;
If you need this jut for display purposes, then leave it as a string with a comma. You can also use Number.toLocaleString() to format numbers for display purposes. But you won't be able to use it in further calculations.
BTW .toFixed() returns a string, so no need to use .toString() after that.
From https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
parseFloat parses its argument, a string, and returns a floating point
number. If it encounters a character other than a sign (+ or -),
numeral (0-9), a decimal point, or an exponent, it returns the value
up to that point and ignores that character and all succeeding
characters. Leading and trailing spaces are allowed.
If the first character cannot be converted to a number, parseFloat
returns NaN.
, is not an expected character so the number is truncated to that.
It's not possible to change the representation of floating point numbers in Javascript, you will need to treat your number as a string if you want to separate decimals with a comma instead of dot.
How can i substract the result i get from x without loosing a decimal place in an html input box??
So, lets say i have x=40.40 and i substract 25, the result should be 15.40 and i am getting 15.4 without that zero. How can i prevent loosing that extra decimal, if i necesarily want to substract that 25 without altering anything else?? (For y i get a 0 with no decimal places and i need 0.00)
document.getElementById("posx").value=(x.toFixed(2)-25.00);
document.getElementById("posy").value=(y1.toFixed(2)-(-2.45));
You'll have to toFixed it after the subtraction
document.getElementById("posx").value = (x - 25.00).toFixed(2);
toFixed converts the value to a string, as numbers don't have zero padding, only the decimals needed to correctly reflect the value of the number.
When you subtract a number from a string, you end up with a number, and as numbers only have the needed decimals, no zero padding, you get 15.4, and once again have to use toFixed to convert it to a string with the decimals you need.
I have just observed that the parseInt function doesn't take care about the decimals in case of integers (numbers containing the e character).
Let's take an example: -3.67394039744206e-15
> parseInt(-3.67394039744206e-15)
-3
> -3.67394039744206e-15.toFixed(19)
-3.6739e-15
> -3.67394039744206e-15.toFixed(2)
-0
> Math.round(-3.67394039744206e-15)
0
I expected that the parseInt will also return 0. What's going on at lower level? Why does parseInt return 3 in this case (some snippets from the source code would be appreciated)?
In this example I'm using node v0.12.1, but I expect same to happen in browser and other JavaScript engines.
I think the reason is parseInt converts the passed value to string by calling ToString which will return "-3.67394039744206e-15", then parses it so it will consider -3 and will return it.
The mdn documentation
The parseInt function converts its first argument to a string, parses
it, and returns an integer or NaN
parseInt(-3.67394039744206e-15) === -3
The parseInt function expects a string as the first argument. JavaScript will call toString method behind the scene if the argument is not a string. So the expression is evaluated as follows:
(-3.67394039744206e-15).toString()
// "-3.67394039744206e-15"
parseInt("-3.67394039744206e-15")
// -3
-3.67394039744206e-15.toFixed(19) === -3.6739e-15
This expression is parsed as:
Unary - operator
The number literal 3.67394039744206e-15
.toFixed() -- property accessor, property name and function invocation
The way number literals are parsed is described here. Interestingly, +/- are not part of the number literal. So we have:
// property accessor has higher precedence than unary - operator
3.67394039744206e-15.toFixed(19)
// "0.0000000000000036739"
-"0.0000000000000036739"
// -3.6739e-15
Likewise for -3.67394039744206e-15.toFixed(2):
3.67394039744206e-15.toFixed(2)
// "0.00"
-"0.00"
// -0
If the parsed string (stripped of +/- sign) contains any character that is not a radix digit (10 in your case), then a substring is created containing all the other characters before such character discarding those unrecognized characters.
In the case of -3.67394039744206e-15, the conversion starts and the radix is determined as base 10 -> The conversion happens till it encounters '.' which is not a valid character in base 10 - Thus, effectively, the conversion happens for 3 which gives the value 3 and then the sign is applied, thus -3.
For implementation logic - http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.2
More Examples -
alert(parseInt("2711e2", 16));
alert(parseInt("2711e2", 10));
TO note:
The radix starts out at base 10.
If the first character is a '0', it switches to base 8.
If the next character is an 'x', it switches to base 16.
It tries to parse strings to integers. My suspicion is that your floats are first getting casted to strings. Then rather than parsing the whole value then rounding, it uses a character by character parsing function and will stop when it gets to the first decimal point ignoring any decimal places or exponents.
Some examples here http://www.w3schools.com/jsref/jsref_parseint.asp
parseInt has the purpose of parsing a string and not a number:
The parseInt() function parses a string argument and returns an
integer of the specified radix (the base in mathematical numeral
systems).
And parseInt calls the function ToString wherein all the non numerical characters are ignored.
You can use Math.round, which also parses strings, and rounds a number to the nearest integer:
Math.round("12.2e-2") === 0 //true
Math.round("12.2e-2") may round up or down based on the value. Hence may cause issues.
new Number("3.2343e-10").toFixed(0) may solve the issue.
Looks like you try to calculate using parseFloat, this will give you the correct answer.
parseInt as it says, returns an integer, whereas parseFloat returns a floating-point number or exponential number:
parseInt(-3.67394039744206e-15) = -3
parseFloat(-3.67394039744206e-15) = -3.67394039744206e-15
console.log('parseInt(-3.67394039744206e-15) = ' , parseInt(-3.67394039744206e-15));
console.log('parseFloat(-3.67394039744206e-15) = ',parseFloat(-3.67394039744206e-15));
I have a simple conversion form from kg to lbs.
html
<input type="text" id="kg" name="kg">
<input type="text" id="lbs" name="lbs">
I have it setup so that the lbs box updates while you type in the kg box with this code.
jQuery
$("#kg").keyup(function(){
$('#lbs').val($('#kg').val()*2.20462);
});
How do I get the lbs value to round to 2 decimals places? I am sure it is something fairly simple but all the examples I found online are for if the number is stored in a variable.
Use toFixed
var string = yourNumber.toFixed(2);
use toFixed:
$('#lbs').val(($('#kg').val()*2.20462).toFixed(2));
number.toFixed( [digits] )
Parameter
digits The number of digits to appear after the decimal point; this
may be a value between 0 and 20, inclusive, and implementations may
optionally support a larger range of values. If this argument is
omitted, it is treated as 0.
Returns
A string representation of number that does not use exponential
notation and has exactly digits digits after the decimal place. The
number is rounded if necessary, and the fractional part is padded with
zeros if necessary so that it has the specified length. If number is
greater than 1e+21, this method simply calls Number.toString() and
returns a string in exponential notation.
also this
(10.8).toFixed(2); // 10.80
var num = 2.4;
alert(num.toFixed(2)); // 2.40
Formatting a number with exactly two decimals in JavaScript