js javascrip 截取小数点后几位

本文介绍JavaScript中处理小数的方法,包括使用Math.round调整精度、toFixed固定小数位数及自定义函数实现精确舍入。适用于开发中各种精度需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发过程中经常遇到要调整小数的格式,如保留小数点后两位等等。方法也颇为常见,备忘如下。

 第一种,利用math.round 

   var original=28.453
1) //round "original" to two decimals
var result=Math.round(original*100)/100;  //returns 28.45
2) // round "original" to 1 decimal
var result=Math.round(original*10)/10;  //returns 28.5

 

第二种,js1.5以上可以利用toFixed(x) ,可指定数字截取小数点后 x位

3) //round "original" to two decimals
var result=original.toFixed(2); //returns 28.45

4) // round "original" to 1 decimal
var result=original.toFixed(1); //returns 28.5

 

以上两种方法最通用,但却无法满足某些特殊要求,比如保留小数点后两位,如果不满两位,不满两位则补零。此时就有了第三种方法。

 

第三种,转换函数,这段代码来源于国外一个论坛。

 

 

[javascript]  view plain copy
  1. function roundNumber(number,decimals) {  
  2.     var newString;// The new rounded number  
  3.     decimals = Number(decimals);  
  4.     if (decimals < 1) {  
  5.         newString = (Math.round(number)).toString();  
  6.     } else {  
  7.         var numString = number.toString();  
  8.         if (numString.lastIndexOf(".") == -1) {// If there is no decimal point  
  9.             numString += ".";// give it one at the end  
  10.         }  
  11.         var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number  
  12.         var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with  
  13.         var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want  
  14.         if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated  
  15.             if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point  
  16.                 while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {  
  17.                     if (d1 != ".") {  
  18.                         cutoff -= 1;  
  19.                         d1 = Number(numString.substring(cutoff,cutoff+1));  
  20.                     } else {  
  21.                         cutoff -= 1;  
  22.                     }  
  23.                 }  
  24.             }  
  25.             d1 += 1;  
  26.         }   
  27.         if (d1 == 10) {  
  28.             numString = numString.substring(0, numString.lastIndexOf("."));  
  29.             var roundedNum = Number(numString) + 1;  
  30.             newString = roundedNum.toString() + '.';  
  31.         } else {  
  32.             newString = numString.substring(0,cutoff) + d1.toString();  
  33.         }  
  34.     }  
  35.     if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string  
  36.         newString += ".";  
  37.     }  
  38.     var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;  
  39.     for(var i=0;i<decimals-decs;i++) newString += "0";  
  40.     //var newNumber = Number(newString);// make it a number if you like  
  41.     document.roundform.roundedfield.value = newString; // Output the result to the form field (change for your purposes)  
  42. }  
 

 

5) //round "original" to two decimals
var result=original.toFixed(2); //returns 28.45

6) // round "original" to 1 decimal
var result=original.toFixed(1); //returns 28.5

 

 

var original=28.4

var result=original.toFixed(2); //returns 28.40

### JavaScript 截取字符串至小数点后两位 在处理数值并将其精确到小数点后两位时,有多种方法可以实现这一目标。以下是几种常见的方式: #### 使用 `substring` 方法 通过将浮点数转换为字符串,再利用 `substring` 函数来提取所需部分。 ```javascript function getFormattedNumber() { var s = 22.127456 + ""; var str = s.substring(0, s.indexOf(".") + 3); console.log(str); // 输出: 22.12 } ``` 这种方法简单直观,但需要注意的是它不会自动四舍五入[^1]。 #### 正则表达式替换法 采用正则表达式匹配模式,能够更灵活地控制输出格式。 ```javascript var a = "28.456322"; var re = /^(\d+\.\d{2})/; var formattedValue = a.replace(re, "$1"); console.log(formattedValue); // 输出: 28.45 ``` 此方式适用于需要严格遵循特定格式的情况,并且同样不涉及四舍五入操作。 #### 利用 `Math.round()` 进行四舍五入 对于希望得到经过四舍五入后的结果而言,这是最常用也是最为推荐的做法之一。 ```javascript var num = 28.127456; var roundedNum = Math.round(num * 100) / 100; console.log(roundedNum.toString()); // 输出: 28.13 ``` 这种方式不仅实现了精度上的调整,还确保了最终结果显示符合预期的数学逻辑。 #### Vue.js 中的数据过滤器应用实例 当涉及到前端框架如Vue.js时,则可以通过自定义过滤器来进行类似的处理。 ```vue <div>{{ datas.cash_total | numFilter }}</div> <script> export default { filters: { numFilter(value) { let realVal = ''; if (!isNaN(value) && value !== '') { realVal = parseFloat(value).toFixed(2); } else { realVal = '--'; } return realVal; }, }, }; </script> ``` 这段代码展示了如何在一个Vue组件内部创建一个名为 `numFilter` 的全局过滤器,用于渲染页面上显示金额或其他需保留两位小数的内容[^2]。 #### 结合正则与 `Number()` 转换函数 如果原始数据是以字符串形式给出的话,还可以考虑先使用正则去除多余的部分后再转回数字类型。 ```javascript let numStr = "3.1415926"; let result = Number(numStr.match(/^\d+(\.\d{0,2})?/)); console.log(result); // 输出: 3.14 ``` 这种组合方案特别适合那些不确定输入源是否总是有效数字的情形下使用[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值