我有一个字符串12345.00,我希望它返回12345.0。

我看了一下trim,但它看起来只是在修剪空白和切片,我不知道这是如何工作的。有什么建议吗?


当前回答

if(str.substring(str.length - 4) == "_bar")
{
    str = str.substring(0, str.length - 4);
}

其他回答

如果要对浮点数进行通用舍入,而不是只修剪最后一个字符:

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

编辑:保罗指出,这似乎有一个内置函数。这种解决方案显然比我的干净得多。使用parseFloat后跟toFixed

对于像您这样的数字,我建议对子字符串执行以下操作:

console.log(parseFloat('12345.00').toFixed(1));

请注意,这实际上会将数字四舍五入,我认为这是需要的,但可能不是:

console.log(parseFloat('12345.46').toFixed(1));

实际上,您可以使用arr.length=2删除数组的最后arr.length-2项,如果数组长度为5,则会删除最后3项。

遗憾的是,这不适用于字符串,但我们可以使用split()拆分字符串,然后在进行任何修改后使用join()连接字符串。

var str='字符串'String.prototype.removeLast=函数(n){var string=this.split(“”)string.length=字符串长度-n返回字符串join(“”)}console.log(str.removeLast(3))

debris = string.split("_") //explode string into array of strings indexed by "_"

debris.pop(); //pop last element off the array (which you didn't want)

result = debris.join("_"); //fuse the remainng items together like the sun

这里有一个我认为在其他答案中没有看到的替代方案,只是为了好玩。

var strArr=“您好,我是字符串”.split(“”);strArr.pop();document.write(strArr.join(“”));

不像切片或子字符串那样清晰或简单,但允许您使用一些不错的数组方法来处理字符串,因此值得了解。