views:

7993

answers:

6

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?

+16  A: 

You can use the substring function

var str = "12345.00";
str.substring(0, str.length - 1);
Jon Erickson
This only gives the last character.
jimyi
I forgot to add the start position. it has been updated.
Jon Erickson
Thanks this is what I needed
Phill Pafford
str.slice(0, - 1);will work too :)
Kheu
@Kheu - the slice notation is much cleaner to me. I was previously using the substring version. Thanks!
Matt Ball
+2  A: 

How about:

var myString = "12345.00";
myString.substring(0, myString.length - 1);
dariom
+9  A: 

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
Paolo Bergantino
A: 

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

PatrikAkerstrand
+2  A: 

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
Jason S
A: 
swift