简体   繁体   中英

How to round down decimal number in javascript

I have this decimal number: 1.12346

I now want to keep only 4 decimals but I want to round down so it will return: 1.1234. Now it returns: 1.1235 which is wrong.

Effectively. I want the last 2 numbers: "46" do round down to "4" and not up to "5"

How is this possible to do?

  var nums = 1.12346; nums = MathRound(nums, 4); console.log(nums); function MathRound(num, nrdecimals) { return num.toFixed(nrdecimals); } 

If you're doing this because you need to print/show a value, then we don't need to stay in number land: turn it into a string, and chop it up:

let nums = 1.12346;

// take advantage of the fact that
// bit operations cause 32 bit integer conversion
let intPart = (nums|0); 

// then get a number that is _always_ 0.something:
let fraction = nums - intPart ;

// and just cut that off at the known distance.
let chopped = `${fraction}`.substring(2,6);

// then put the integer part back in front.
let finalString = `${intpart}.${chopped}`;

Of course, if you're not doing this for presentation, the question "why do you think you need to do this" (because it invalidates subsequent maths involving this number) should probably be answered first, because helping you do the wrong thing is not actually helping, but making things worse.

This is the same question as How to round down number 2 decimal places? . You simply need to make the adjustments for additional decimal places.

Math.floor(1.12346 * 10000) / 10000

 console.log(Math.floor(1.12346 * 10000) / 10000); 

If you want this as a reusable function, you could do:

 function MathRound (number, digits) { var adjust = Math.pow(10, digits); // or 10 ** digits if you don't need to target IE return Math.floor(number * adjust) / adjust; } console.log(MathRound(1.12346, 4)); 

I think this will do the trick. Essentially correcting the round up.

 var nums = 1.12346; nums = MathRound(nums, 4); console.log(nums); function MathRound(num, nrdecimals) { let n = num.toFixed(nrdecimals); return (n > num) ? n-(1/(Math.pow(10,nrdecimals))) : n; } 

 var nums = 1.12346; var dec = 10E3; var intnums = Math.floor(nums * dec); var trim = intnums / dec; console.log(trim); 

var num = 1.2323232;
converted_num = num.toFixed(2);  //upto 2 precision points
o/p : "1.23"

To get the float num : 
converted_num = parseFloat(num.toFixed(2));
o/p : 1.23

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM