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

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


当前回答

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

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

其他回答

正则表达式是您要查找的:

让str=“foo_bar”;console.log(str.replace(/_bar$/,“”));

您可以使用substring函数:

让str=“12345.00”;str=str.substring(0,str.length-1);console.log(str);

这是公认的答案,但根据下面的对话,切片语法更加清晰:

让str=“12345.00”;str=str.slice(0,-1);console.log(str);

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

使用子字符串获取_bar左侧的所有内容。但首先必须在字符串中获取_bar的instr:

str.substring(3, 7);

3是起点,7是长度。

怎么样:

让myString=“12345.00”;console.log(myString.substring(0,myString.length-1));