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

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


当前回答

使用JavaScript的切片函数:

let string='foo_bar';string=string.spice(0,-4);//在此处切下最后四个字符console.log(字符串);

这可以用于删除任何长度字符串末尾的“_bar”。

其他回答

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

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

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

最简单的方法是使用字符串的切片方法,该方法允许负位置(对应于从字符串末尾的偏移):

const s = "your string";
const withoutLastFourChars = s.slice(0, -4);

如果需要更一般的方法来删除最后一个下划线之后的所有内容(包括),可以执行以下操作(只要确保s至少包含一个下划线):

consts=“your_string”;const withoutLastChunk=s.slice(0,s.lastIndexOf(“_”));console.log(不带LastChunk);

https://stackoverflow.com/questions/34817546/javascript-how-to-delete-last-two-characters-in-a-string

如果不需要空间,只需使用修剪

"11.01 °C".slice(0,-2).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

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