I have a string 12345.00 would like it to return 12345.0
I have looked at trim but looks only to trim whitespace and slice which I don't see how this would work. Any suggs?
I have a string 12345.00 would like it to return 12345.0
I have looked at trim but looks only to trim whitespace and slice which I don't see how this would work. Any suggs?
You can use the substring function
var str = "12345.00";
str.substring(0, str.length - 1);
How about:
var myString = "12345.00";
myString.substring(0, myString.length - 1);
For a number like your example, I would recommend doing this over substring
:
alert(parseFloat('12345.00').toFixed(1)); // 12345.0
Do note that this will actually round the number, though, which I would imagine is desired but maybe not:
alert(parseFloat('12345.46').toFixed(1)); // 12345.5
If you want to do generic rounding of floats, instead of just trimming the last character:
var float1 = 12345.00,
float2 = 12345.4567,
float3 = 12345.982;
var MoreMath = {
/**
* Rounds a value to the specified number of decimals
* @param float value The value to be rounded
* @param int nrDecimals The number of decimals to round value to
* @return float value rounded to nrDecimals decimals
*/
round: function (value, nrDecimals) {
var x = nrDecimals > 0 ? 10 * parseInt(nrDecimals, 10) : 1;
return Math.round(value * x) / x;
}
}
MoreMath.round(float1, 1) => 12345.0
MoreMath.round(float2, 1) => 12345.5
MoreMath.round(float3, 1) => 12346.0
EDIT: Seems like there exists a built in function for this, as Paolo points out. That solution is obviously much cleaner than mine. Use parseFloat followed by toFixed
You can use slice! You just have to make sure you know how to use it. Positive #s are relative to the beginning, negative numbers are relative to the end.
js>"12345.00".slice(0,-1)
12345.0