本文翻译自:JavaScript math, round to two decimal places [duplicate]

This question already has answers here : 这个问题已经在这里有了答案 :
Closed 2 years ago . 2年前关闭。
Round to at most 2 decimal places (only if necessary) (71 answers) 四舍五入至小数点后两位(仅在必要时) (71个答案)

I have the following JavaScript syntax: 我有以下JavaScript语法:

var discount = Math.round(100 - (price / listprice) * 100);

This rounds up to the whole number. 这四舍五入为整数。 How can I return the result with two decimal places? 如何返回两位小数的结果?


#1楼

参考:https://stackoom.com/question/148cC/JavaScript数学-四舍五入到小数点后两位-重复


#2楼

NOTE - See Edit 4 if 3 digit precision is important 注-如果3位数精度很重要,请参阅编辑4

var discount = (price / listprice).toFixed(2);

toFixed will round up or down for you depending on the values beyond 2 decimals. toFixed将为您舍入或舍入,具体取决于2位小数之后的值。

Example: http://jsfiddle.net/calder12/tv9HY/ 示例: http : //jsfiddle.net/calder12/tv9HY/

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed 文档: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

Edit - As mentioned by others this converts the result to a string. 编辑 -正如其他人所提到的,它将结果转换为字符串。 To avoid this: 为了避免这种情况:

var discount = +((price / listprice).toFixed(2));

Edit 2 - As also mentioned in the comments this function fails in some precision, in the case of 1.005 for example it will return 1.00 instead of 1.01. 编辑2-正如注释中所提到的,此函数在某种程度上会失败,例如在1.005的情况下,它将返回1.00而不是1.01。 If accuracy to this degree is important I've found this answer: https://stackoverflow.com/a/32605063/1726511 Which seems to work well with all the tests I've tried. 如果准确性在这个程度上很重要,那么我已经找到了这个答案: https : //stackoverflow.com/a/32605063/1726511这似乎与我尝试过的所有测试均能很好地工作。

There is one minor modification required though, the function in the answer linked above returns whole numbers when it rounds to one, so for example 99.004 will return 99 instead of 99.00 which isn't ideal for displaying prices. 不过,需要进行一些小的修改,上面链接的答案中的函数在四舍五入时返回整数,因此例如99.004将返回99而不是99.00,这对于显示价格而言并不理想。

Edit 3 - Seems having the toFixed on the actual return was STILL screwing up some numbers, this final edit appears to work. 编辑3-似乎在实际收益表上固定了TOST仍在搞砸一些数字,此最终编辑似乎有效。 Geez so many reworks! 哎呀,这么多返工!

   var discount = roundTo((price / listprice), 2);function roundTo(n, digits) {if (digits === undefined) {digits = 0;}var multiplicator = Math.pow(10, digits);n = parseFloat((n * multiplicator).toFixed(11));var test =(Math.round(n) / multiplicator);return +(test.toFixed(digits));}

See Fiddle example here: https://jsfiddle.net/calder12/3Lbhfy5s/ 请参阅此处的小提琴示例: https : //jsfiddle.net/calder12/3Lbhfy5s/

Edit 4 - You guys are killing me. 编辑4-你们杀了我。 Edit 3 fails on negative numbers, without digging into why it's just easier to deal with turning a negative number positive before doing the rounding, then turning it back before returning the result. Edit 3对负数失败,而没有深入研究为什么在进行舍入之前将负数变为正数更容易处理,然后在返回结果之前将其变回正好。

function roundTo(n, digits) {var negative = false;if (digits === undefined) {digits = 0;}if( n < 0) {negative = true;n = n * -1;}var multiplicator = Math.pow(10, digits);n = parseFloat((n * multiplicator).toFixed(11));n = (Math.round(n) / multiplicator).toFixed(2);if( negative ) {    n = (n * -1).toFixed(2);}return n;
}

Fiddle: https://jsfiddle.net/3Lbhfy5s/79/ 小提琴: https : //jsfiddle.net/3Lbhfy5s/79/


#3楼

尝试使用discount.toFixed(2);


#4楼

To get the result with two decimals, you can do like this : 要获得两个小数点的结果,可以这样:

var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;

The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result. 要取整的值乘以100以保留前两位数字,然后我们除以100得到实际结果。


#5楼

If you use a unary plus to convert a string to a number as documented on MDN . 如果您使用一元加号将字符串转换为MDN上记录的数字。

For example: +discount.toFixed(2) 例如: +discount.toFixed(2)


#6楼

A small variation on the accepted answer. 接受的答案略有不同。 toFixed(2) returns a string, and you will always get two decimal places. toFixed(2)返回一个字符串,并且您将始终得到两个小数位。 These might be zeros. 这些可能为零。 If you would like to suppress final zero(s), simply do this: 如果您想取消最后的零,只需执行以下操作:

var discount = + ((price / listprice).toFixed(2));

Edited: I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values. 编辑:我刚刚发现了Firefox 35.0.1中的一个bug,这意味着以上内容可能为NaN提供了一些值。
I've changed my code to 我已将代码更改为

var discount = Math.round(price / listprice * 100) / 100;

This gives a number with up to two decimal places. 这给出了一个最多有两个小数位的数字。 If you wanted three, you would multiply and divide by 1000, and so on. 如果要三个,则可以乘以1000,以此类推。
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first. OP总是希望小数点后两位,但是如果toFixed()在Firefox中损坏,则需要先修复。
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388 参见https://bugzilla.mozilla.org/show_bug.cgi?id=1134388

JavaScript数学,四舍五入到小数点后两位[重复]相关推荐

  1. 四舍五入到小数点后两位[重复]

    本文翻译自:Round a double to 2 decimal places [duplicate] This question already has answers here : 这个问题已经 ...

  2. 如何在 JavaScript 中将数字四舍五入到小数点后两位

    点击上方 前端Q,关注公众号 回复加群,加入前端Q技术交流群 英文 | https://codingbeauty.medium.com/javascript-round-number-to-2-dec ...

  3. java 常用四舍五入保留小数点后两位方法

    java 常用四舍五入保留小数点后两位方法 1 . Math.round double num = Math.round(5.2544555 * 100) * 0.01; System.out.pri ...

  4. excel 公式 单引号 concat_Excel四舍五入到小数点后两位,不显示0,或如何使0成为短划线...

    在Excel中有三种舍入到指定小数位数的方法.一是使用数字格式,二是设置格式单元格,三是使用圆函数等函数.这三种方法都是自动四舍五入的.前两种方法还保留整数的指定小数位数,即保留小数点后的所有零:后一 ...

  5. java 四舍五入保留小数点后两位

    方式一: double f = 3.1516; BigDecimal b = new BigDecimal(f); double f1 = b.setScale(2, BigDecimal.ROUND ...

  6. js除法四舍五入保留小数点后两位写法

    原文连接 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> &l ...

  7. C++四舍五入以及小数点后两位进行舍入

    题目要求求成绩的平均分,最后要四舍五入. 很有灵魂的四舍五入 int re = (int) (1.0*sum/n * 100 + 0.5);double re2 = (double) 1.0*re/1 ...

  8. 显示一个数字到小数点后两位

    将PHP字符串四舍五入到小数点后两位的正确方法是什么? $number = "520"; // It's a string from a database$formatted_nu ...

  9. js中如何截取小数点后两位数字

    用Javascript取float型小数点后两位,例22.127456取成22.13,如何做? 1. 最笨的办法. 1 function  get() 2 { 3    var s = 22.1274 ...

最新文章

  1. 手机密钥连接linux主机
  2. Linux下的TCP Wrapper机制
  3. ABAP--如何快速从BSEG读取数据
  4. c语言首尾指针相同 则,6.C语言指针练习题.doc
  5. hdu 5274(树链剖分)
  6. zookeeper的名词复盘-数据模型
  7. 5,线程池,进程池,协程,IO模型
  8. 使用MybatisPlus在实体中添加数据库表中不存在的字段
  9. 行列式算法c语言,新手作品:行列式计算C语言版
  10. ERP开发分享 1 数据库表设计
  11. java 字符串和整型的相互转换
  12. QQ聊天记录恢复深度研究
  13. 小程序微信JSAPI支付进行退款操作
  14. 通过有线网卡共享无线网络
  15. 互联网公司指南 上海篇: 字节跳动
  16. 强化学习入门1—多臂老虎机Multi-armed Bandits
  17. POI设置excel格式为文本格式
  18. 如何调用百度地图API---定位、显示热力图、路径导航等(很方便很强大)
  19. C语言例题——简易计算器
  20. 04 从中兴研发主管坠楼来看,什么是程序员的不能承受之重?

热门文章

  1. 相机原理updateTexImage
  2. 求解射线交点的完整代码
  3. android xml 文件里面的宽度Match_Parent 被 替换成了wrap_content
  4. 【Java源码分析】HashMap源码分析
  5. 计算机原理及其应用的题,微机原理及应用习题与答案(4)
  6. Android之PullToRefresh控件源码解析
  7. Postman 调试技巧
  8. kettle分批处理大表数据_kettle-批量同步表数据
  9. python自动化运维开发-Python自动化运维开发----基础(七)元组
  10. 2018-08-19-Python全栈开发day43-正反选练习