Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate decimal number (as strings) to a fixed number of places

I want to truncate numbers (given as strings) to a fixed number of decimal places. The numbers can be negative (with a minus sign), positive (no sign). I'd prefer to round the numbers properly and keep trailing zeroes. I want the same number of decimal places, no matter how long the whole number is. The numbers will be stored back as strings.

For example:

140.234234234 -> 140.234
1.123123 -> 1.123
-12.789789 -> -12.790
like image 794
nevan king Avatar asked Jan 18 '13 17:01

nevan king


People also ask

How do I truncate decimal places?

To truncate a number to 1 decimal place, miss off all the digits after the first decimal place. To truncate a number to 2 decimal places, miss off all the digits after the second decimal place.

How do I truncate decimal places in SQL?

Overview of SQL TRUNCATE() function The TRUNCATE() function returns n truncated to d decimal places. If you skip d , then n is truncated to 0 decimal places. If d is a negative number, the function truncates the number n to d digits left to the decimal point.


1 Answers

First parse them as floats, then format with toFixed:

var nums = [
    "140.234234234", // -> 140.234
    "1.123123", // -> 1.123
    "-12.789789" // -> -12.790
];

nums.forEach(function(n) {
    console.log(parseFloat(n).toFixed(3));
});

http://codepen.io/anon/pen/IvxmA

like image 82
bfavaretto Avatar answered Sep 27 '22 20:09

bfavaretto