javascript - 将数字截断为两位小数,而不进行舍入

假设我的值为15.7784514,我希望将其显示为15.77而不进行舍入。

varnum=parseFloat(15.7784514);document.write(num.toFixed(1)+"
");document.write(num.toFixed(2)+"
");document.write(num.toFixed(3)+"
");document.write(num.toFixed(10));

结果是 -

15.815.7815.77815.7784514000

我如何显示15.77?

tempid asked 2019-04-28T15:34:16Z

27个解决方案

186 votes

将数字转换为字符串,将数字与第二个小数位匹配:

functioncalc(theform){varnum=theform.original.value,rounded=theform.roundedvarwith2Decimals=num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]rounded.value=with2Decimals}">calc(theform){     var num = theform.original.value,rounded = theform.rounded     var with2Decimals = num.toString()。match(/ ^ - ?\ d +(?:\。\ d {0,2})?/)[0]     rounded.value = with2Decimals}

onsubmit =“return calc(this)”>原始编号:< input name =“original”type =“text”onkeyup =“calc(form)”onchange =“calc(form)”/>< br />“Rounded”数字:< input name =“rounded”type =“text”placeholder =“readonly”readonly></形式>

运行代码段隐藏结果

展开代码段

toFixed方法在某些情况下失败,与toString不同,所以要非常小心。

Gumbo answered 2019-04-28T15:34:57Z

41 votes

2016年11月5日更新

新答案,始终准确

functiontoFixed(num,fixed){varre=newRegExp('^-?\\d+(?:\.\\d{0,'+(fixed||-1)+'})?');returnnum.toString().match(re)[0];}

由于javascript中的浮点数学将始终具有边缘情况,因此以前的解决方案在大多数情况下都是准确的,这是不够好的。有一些解决方案,如num.toPrecision,BigDecimal.js和accounting.js。然而,我相信仅仅解析字符串将是最简单且始终准确的。

基于@Gumbo接受的答案中写得好的正则表达式的更新,这个新的toFixed函数将始终按预期工作。

老答案,并不总是准确的。

滚动你自己的固定功能:

functiontoFixed(num,fixed){fixed=fixed||0;fixed=Math.pow(10,fixed);returnMath.floor(num*fixed)/fixed;}

guya answered 2019-04-28T15:36:02Z

24 votes

我选择写这个来手动删除字符串的余数,所以我不必处理数字带来的数学问题:

num=num.toString();//If it's not already a Stringnum=num.slice(0,(num.indexOf("."))+3);//With 3 exposing the hundredths placeNumber(num);//If you need it back as a Number

这将给你“15.77”与num = 15.7784514;

ベンノスケ answered 2019-04-28T15:36:37Z

12 votes

parseInt比Math.floor快

functionfloorFigure(figure,decimals){if(!decimals)decimals=2;vard=Math.pow(10,decimals);return(parseInt(figure*d)/d).toFixed(decimals);};floorFigure(123.5999)=>"123.59"floorFigure(123.5999,3)=>"123.599"

Martin Varmus answered 2019-04-28T15:37:03Z

9 votes

2017年10月

对于任何n≥0,将任意数字截断(不舍入)到第n个十进制数字并将其转换为精确n个十进制数字的字符串的一般解决方案。

functiontoFixedTrunc(value,n){constv=value.toString().split('.');if(n<=0)returnv[0];letf=v[1]||'';if(f.length>n)return`${v[0]}.${f.substr(0,n)}`;while(f.length

以下是n = 2的一些测试(包括OP请求的测试):

0=>0.000.01=>0.010.2372=>0.230.5839=>0.580.999=>0.991=>1.001.01=>1.012=>2.002.551=>2.552.5=>2.502.99999=>2.994.27=>4.2715.7784514=>15.77123.5999=>123.59

请注意,虽然上述工作总是如此,但纯数字方法不会。 例如,考虑以下函数(或任何类似的函数):

functiontoFixedTrunc(value,n){constf=Math.pow(10,n);return(Math.trunc(value*f)/f).toFixed(n);}

虽然在概念上是正确的,但是会因一些无理数而失败,例如: 4.27,由于数字在内部表示的方式。

SC1000 answered 2019-04-28T15:37:55Z

5 votes

这些解决方案确实有效,但对我来说似乎不必要地复杂化。 我个人喜欢使用模运算符来获得除法运算的剩余部分,并删除它。 假设num = 15.7784514:

num-=num%.01;

这相当于说num = num - (num%.01)。

jtrick answered 2019-04-28T15:38:31Z

5 votes

这里的答案对我没有帮助,它继续四舍五入或给我错误的小数。

我的解决方案将您的小数转换为字符串,提取字符然后将整个事物作为数字返回。

functionDec2(num){num=String(num);if(num.indexOf('.')!==-1){varnumarr=num.split(".");if(numarr.length==1){returnNumber(num);}else{returnNumber(numarr[0]+"."+numarr[1].charAt(0)+numarr[1].charAt(1));}}else{returnNumber(num);}}Dec2(99);// 99Dec2(99.9999999);// 99.99Dec2(99.35154);// 99.35Dec2(99.8);// 99.8Dec2(10265.985475);// 10265.98

David D answered 2019-04-28T15:39:05Z

4 votes

以下代码对我非常有用:

num.toString().match(/.\*\\..{0,2}|.\*/)[0];

MISSIRIA answered 2019-04-28T15:39:31Z

4 votes

我的正数版本:

functiontoFixed_norounding(n,p){varresult=n.toFixed(p);returnresult<=n?result:(result-Math.pow(0.1,p)).toFixed(p);}

快速,漂亮,明显。

Alpha and Omega answered 2019-04-28T15:40:05Z

4 votes

这很简单

number=parseInt(number*100)/100;

Imran Pollob answered 2019-04-28T15:40:35Z

3 votes

num=19.66752f=num.toFixed(3).slice(0,-1)alert(f)

这将返回19.66

Alex Peng answered 2019-04-28T15:41:02Z

3 votes

我使用以下简单方法修复 -

varnum=15.7784514;Math.floor(num*100)/100;

结果将是15.77

oms answered 2019-04-28T15:41:35Z

2 votes

这个给你。 答案显示了另一种解决问题的方法:

// For the sake of simplicity, here is a complete function:functiontruncate(numToBeTruncated,numOfDecimals){vartheNumber=numToBeTruncated.toString();varpointIndex=theNumber.indexOf('.');return+(theNumber.slice(0,pointIndex>-1?++numOfDecimals+pointIndex:undefined));}

注意在最终表达式之前使用+。 那就是将截断的切片字符串转换回数字类型。

希望能帮助到你!

Jakub Barczyk answered 2019-04-28T15:42:11Z

2 votes

截断没有零

functiontoTrunc(value,n){returnMath.floor(value*Math.pow(10,n))/(Math.pow(10,n));}

要么

functiontoTrunc(value,n){x=(value.toString()+".0").split(".");returnparseFloat(x[0]+"."+x[1].substr(0,n));}

测试:

toTrunc(17.4532,2)//17.45toTrunc(177.4532,1)//177.4toTrunc(1.4532,1)//1.4toTrunc(.4,2)//0.4

用零截断

functiontoTruncFixed(value,n){returntoTrunc(value,n).toFixed(n);}

测试:

toTrunc(17.4532,2)//17.45toTrunc(177.4532,1)//177.4toTrunc(1.4532,1)//1.4toTrunc(.4,2)//0.40

ShAkKiR answered 2019-04-28T15:42:51Z

2 votes

一个简单的方法是下一步,但必须确保amount参数以字符串形式给出。

functiontruncate(amountAsString,decimals=2){vardotIndex=amountAsString.indexOf('.');vartoTruncate=dotIndex!==-1&&(amountAsString.length>dotIndex+decimals+1);varapproach=Math.pow(10,decimals);varamountToTruncate=toTruncate?amountAsString.slice(0,dotIndex+decimals+1):amountAsString;returntoTruncate?Math.floor(parseFloat(amountToTruncate)*approach)/approach:parseFloat(amountAsString);

}

console.log(truncate("7.99999"));//OUTPUT ==> 7.99console.log(truncate("7.99999",3));//OUTPUT ==> 7.999console.log(truncate("12.799999999999999"));//OUTPUT ==> 7.99

Felipe Santa answered 2019-04-28T15:43:19Z

1 votes

另一个单线解决方案:

number=Math.trunc(number*100)/100

我使用100因为你想要截断到第二个数字,但更灵活的解决方案是:

number=Math.trunc(number*Math.pow(10,digits))/Math.pow(10,digits)

其中digits是要保留的小数位数。

RemiV2 answered 2019-04-28T15:43:59Z

1 votes

这对我很有用。 我希望它也能解决你的问题。

functiontoFixedNumber(number){constspitedValues=String(number.toLocaleString()).split('.');letdecimalValue=spitedValues.length>1?spitedValues[1]:'';decimalValue=decimalValue.concat('00').substr(0,2);return'$'+spitedValues[0]+'.'+decimalValue;}// 5.56789 ----> $5.56// 0.342 ----> $0.34// -10.3484534 ----> $-10.34// 600 ----> $600.00

Convert
">convertNumber(){   var result = toFixedNumber(document.getElementById(“valueText”)。value);   document.getElementById(“resultText”)。value = result;}function toFixedNumber(number){         const spitedValues = String(number.toLocaleString())。split('。');         let decimalValue = spitedValues.length&gt; 1? spitedValues [1]:'';         decimalValue = decimalValue.concat('00')。substr(0,2);         返回'$'+ spitedValues [0] +'。' + decimalValue;}
Convert
">&lt; input type =“text”id =“valueText”placeholder =“此处输入值”&gt;  &LT峰; br&GT;   &lt; button onclick =“convertNumber()”&gt;转换&lt; / button&gt;  &LT峰; br&GT;&LT; HR&GT;   &lt; input type =“text”id =“resultText”placeholder =“result”readonly =“true”&gt;&LT;/ DIV&GT;

运行代码段隐藏结果

展开代码段

Sandaru answered 2019-04-28T15:44:49Z

0 votes

滚动你自己的Math.floor功能:正值Math.ceil工作正常。

functiontoFixed(num,fixed){fixed=fixed||0;fixed=Math.pow(10,fixed);returnMath.floor(num*fixed)/fixed;}

对于负值Math.floor是圆的值。 所以你可以用Math.ceil代替。

例,

Math.ceil(-15.778665*10000)/10000=-15.7786Math.floor(-15.778665*10000)/10000=-15.7787// wrong.

Boopathi Sakthivel answered 2019-04-28T15:45:30Z

0 votes

Gumbo的第二个解决方案,使用正则表达式,确实有效,但由于正则表达式,它很慢。 由于浮点数不精确,Gumbo的第一个解决方案在某些情况下失败。 请参阅JSFiddle以获取演示和基准。 第二种解决方案在我当前的系统上每次呼叫大约需要1636纳秒,即3.30 GHz的英特尔酷睿i5-2500 CPU。

我写的解决方案涉及添加一个小补偿来处理浮点不精确。 它基本上是瞬时的,即在纳秒级。 我每次调用时钟为2纳秒,但JavaScript定时器不是非常精确或粒度。 这是JS小提琴和代码。

functiontoFixedWithoutRounding(value,precision){varfactorError=Math.pow(10,14);varfactorTruncate=Math.pow(10,14-precision);varfactorDecimal=Math.pow(10,precision);returnMath.floor(Math.floor(value*factorError+1)/factorTruncate)/factorDecimal;}varvalues=[1.1299999999,1.13,1.139999999,1.14,1.14000000001,1.13*100];for(vari=0;i "+toFixedWithoutRounding(value,2));}for(vari=0;i "+toFixedWithoutRounding(value,4));}console.log("type of result is "+typeoftoFixedWithoutRounding(1.13*100/100,2));// Benchmarkvarvalue=1.13*100;varstartTime=newDate();varnumRun=1000000;varnanosecondsPerMilliseconds=1000000;for(varrun=0;run

Daniel Barbalace answered 2019-04-28T15:46:07Z

0 votes

我使用(num-0.05).toFixed(1)得到第二个十进制小数。

王景飞 answered 2019-04-28T15:46:36Z

0 votes

以David D的答案为基础:

functionNumberFormat(num,n){varnum=(arguments[0]!=null)?arguments[0]:0;varn=(arguments[1]!=null)?arguments[1]:2;if(num>0){num=String(num);if(num.indexOf('.')!==-1){varnumarr=num.split(".");if(numarr.length>1){if(n>0){vartemp=numarr[0]+".";for(vari=0;i

Charles Robertson answered 2019-04-28T15:47:03Z

0 votes

获得两个没有舍入的浮点更可靠。

参考答案

varnumber=10.5859;varfixed2FloatPoints=parseInt(number*100)/100;console.log(fixed2FloatPoints);">数字= 10.5859;var fixed2FloatPoints = parseInt(number * 100)/ 100;的console.log(fixed2FloatPoints);

运行代码段隐藏结果

展开代码段

谢谢 !

Jaydeep Mor answered 2019-04-28T15:48:02Z

0 votes

已经有正则表达式和算术计算的一些合适的答案,你也可以试试这个

functionmyFunction(){varstr=12.234556;str=str.toString().split('.');varres=str[1].slice(0,2);document.getElementById("demo").innerHTML=str[0]+'.'+res;}// output: 12.23

anik islam Shojib answered 2019-04-28T15:48:29Z

0 votes

这是用字符串做的

exportfunctionwithoutRange(number){conststr=String(number);constdotPosition=str.indexOf('.');if(dotPosition>0){constlength=str.substring().length;constend=length>3?3:length;returnstr.substring(0,dotPosition+end);}returnstr;}

Kishan Vaghela answered 2019-04-28T15:48:56Z

0 votes

只是截断数字:

functiontruncDigits(inputNumber,digits){constfact=10**digits;returnMath.floor(inputNumber*fact)/fact;}

Aral Roca answered 2019-04-28T15:49:24Z

-1 votes

谢谢Martin Varmus

functionfloorFigure(figure,decimals){if(!decimals)decimals=2;vard=Math.pow(10,decimals);return((figure*d)/d).toFixed(decimals);};floorFigure(123.5999)=>"123.59"floorFigure(123.5999,3)=>"123.599"

我做了一个简单的更新,我得到了适当的舍入。 更新如下

return((figure*d)/d).toFixed(decimals);

删除parseInt()函数

Jakir Hosen Khan answered 2019-04-28T15:50:08Z

-1 votes

这是保存.toFixed([digits])函数的另一个变量,没有舍入float变量:

Number.prototype.toRealFixed=function(digits){returnMath.floor(this.valueOf()*Math.pow(10,digits))/Math.pow(10,digits);};

并致电:

varfloat_var=0.02209062;float_var.toRealFixed();

AlexxKur answered 2019-04-28T15:50:45Z

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐