我有一个字符串12345.00,我希望它返回12345.0。
我看了一下trim,但它看起来只是在修剪空白和切片,我不知道这是如何工作的。有什么建议吗?
我有一个字符串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
其他回答
表演
今天2020.05.13我在MacOs High Sierra v10.13.6上对Chrome v81.0、Safari v13.1和Firefox v76.0上选择的解决方案进行了测试。
结论
切片(0,-1)(D)是短字符串和长字符串的快速或最快解决方案,建议作为快速跨浏览器解决方案基于子字符串(C)和子字符串(E)的解决方案是快速的基于正则表达式(A,B)的解决方案是慢/中快的解决方案B、F和G对于长字符串来说很慢解决方案F对于短字符串最慢,对于长字符串最慢
细节
我对解决方案A、B、C、D、E(ext)、F、G(my)进行了两次测试
对于8个字符的短字符串(来自OP问题)-您可以在这里运行对于1M长的字符串-您可以在这里运行
解决方案在以下片段中介绍
函数A(str){return str.replace(/.$/,“”);}函数B(str){返回str.match(/(.*).$/)[1];}函数C(str){返回str.substring(0,str.length-1);}函数D(str){返回str.slice(0,-1);}函数E(str){返回str.substr(0,str.length-1);}函数F(str){设s=str.split(“”);s.pop();return s.join(“”);}函数G(str){让s=“”;对于(设i=0;i<str.length-1;i++)s+=str[i];返回s;}// ---------//测试// ---------let log=(f)=>console.log(`${f.name}:${f(“12345.00”)}`);[A,B,C,D,E,F,G].map(F=>log(F));此代码段仅显示源
以下是Chrome短字符串的示例结果
实际上,您可以使用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))
如果要对浮点数进行通用舍入,而不是只修剪最后一个字符:
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
https://stackoverflow.com/questions/34817546/javascript-how-to-delete-last-two-characters-in-a-string
如果不需要空间,只需使用修剪
"11.01 °C".slice(0,-2).trim()
尝试使用toFixed
const str = "12345.00";
return (+str).toFixed(1);