Lee
Lee

Reputation: 23

Rounding up and rounding down bill amount

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.

Upvotes: 2

Views: 1288

Answers (3)

shareef
shareef

Reputation: 9581

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()

Upvotes: 1

rob
rob

Reputation: 10117

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.

Upvotes: 4

Abhijit
Abhijit

Reputation: 63757

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

Upvotes: 2

Related Questions