我有一个字符串12345.00,我希望它返回12345.0。
我看了一下trim,但它看起来只是在修剪空白和切片,我不知道这是如何工作的。有什么建议吗?
我有一个字符串12345.00,我希望它返回12345.0。
我看了一下trim,但它看起来只是在修剪空白和切片,我不知道这是如何工作的。有什么建议吗?
当前回答
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 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
你可以用切片!你只需要确保你知道如何使用它。正数是相对于开头的,负数是相对于结尾的。
js>"12345.00".slice(0,-1)
12345.0
使用JavaScript的切片函数:
let string='foo_bar';string=string.spice(0,-4);//在此处切下最后四个字符console.log(字符串);
这可以用于删除任何长度字符串末尾的“_bar”。
如果要删除接近字符串末尾的内容(对于大小可变的字符串),可以将slice()和substr()组合起来。
我有一个动态构建的带有标记的字符串,其中有一个用逗号分隔的锚标记列表。字符串类似于:
var str = "<a>text 1,</a><a>text 2,</a><a>text 2.3,</a><a>text abc,</a>";
要删除最后一个逗号,我执行了以下操作:
str = str.slice(0, -5) + str.substr(-4);