Rounding up and rounding down bill amount

感情迁移 提交于 2021-01-28 04:48:35

问题


I'm facing a problem to get the digit of a number after decimal point. I need the digit to do if else statement.

Here is an example:

31.30 = 31.30
31.31 = 31.30
31.32 = 31.30
31.33 = 31.35
31.34 = 31.35
31.35 = 31.35
31.36 = 31.35
31.37 = 31.35
31.38 = 31.40
31.39 = 31.30   

So, I need to get the second digit after decimal point. Then, i can use the digit to do if else statement. This rounding issue is happening in Malaysia.


回答1:


Something like this might work for doing the rounding to the nearest 5 cents, although then you may need to format the output to have the proper number of digits past the decimal point:

var origVal = 31.34;
var roundedVal = Math.round(origVal*20)/20;

Which would give you 31.35, i.e., rounded to the nearest nickel.

This seems a little more direct than getting the digit and doing an if/else.




回答2:


Simply try Math.round(x*100%10)




回答3:


for a part of your question

you can round javascript to specific precision by

Link :Number rounding in JavaScript

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



3) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000  //returns 8.111

from How can I round down a number in Javascript?

Round towards negative infinity - Math.floor()

+3.5 => +3.0 -3.5 => -4.0 Round towards zero - usually called Truncate(), but not supported by JavaScript - can be emulated by using Math.ceil() for negative numbers and Math.floor() for positive numbers.

+3.5 => +3.0 using Math.floor() -3.5 => -3.0 using Math.ceil()



来源:https://stackoverflow.com/questions/8352834/rounding-up-and-rounding-down-bill-amount

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!