Jim Blum
Jim Blum

Reputation: 2646

Javascript function to get a convert a number to X number of digits only

I want to use a javascript function which gets a real number, and makes the whole number X digits, (except if the integer part is larger).

I will give you some examples. Suppose the function I am looking for is f(a,b) where a is the number we have, and b is the digits we want to be converted:

f(1.23456,5)    =>1.2345
f(1.23456,6)    =>1.23456
f(1.23456,7)    =>1.234560
f(123.45,5)     =>123.45
f(12345.678,5)  =>12345
f(1234567.89,5) =>1234567

Is there any function which does that?

The closer function to this I guess is Number(N).toFixed(X), which fixes only the right part a real number to X digits, but not the whole number..

Do you know how to do that?

Upvotes: 2

Views: 206

Answers (6)

user3246890
user3246890

Reputation: 139

This function is short and does just what you want.

javascript:

function truncate(number, truncateTo)
{alert(number.substring(0, truncateTo));}

HTML (button i made if you want to try it out):

<button onclick="truncate('1234', 2)">Truncate</button>

Upvotes: 1

adeneo
adeneo

Reputation: 318282

I'd do something like this

function f(numb, dec) {
    var sub  = Math.floor(numb % 10),
        mult = Math.pow(10, (dec-sub));
    return (sub > dec) ? parseInt(numb, 10) : parseInt(numb*mult, 10) / mult;
}

FIDDLE

It doesn't add trailing zeros after the decimal point, as that's not possible with numbers, you'd have to convert the numbers to strings, which sort of defeats the purpose of this, but if you really want strings you can do

function f(numb, dec) {
    var sub  = Math.floor(numb % 10),
        mult = Math.pow(10, (dec-sub));

    if (sub > dec) return parseInt(numb, 10).toString();
    var n = (parseInt(numb*mult, 10) / mult).toString();
    while (n.replace('.','').length < dec) {n = n+'0';}

    return n;
}

FIDDLE

Upvotes: 1

Patrick Evans
Patrick Evans

Reputation: 42736

toPrecision does mostly what you want, the only difference is that it rounds to the last digit:

var n = 1.23456;
console.log( n.toPrecision(5) ); //outputs 1.2346
n = 1234.56;
console.log( n.toPrecision(4) ); //outputs 1235

Do not know if there is a way to prevent the rounding, if rounding is unwanted... will update answer if i can find a way or someone graciously mentions a way to prevent the rounding without having to do the string manipulations.

Upvotes: 4

Strille
Strille

Reputation: 5781

function f(num, chars) {
    var numOfFloats = chars - String(Math.floor(num)).length;
    if (numOfFloats > 0) {
        return new Number(num).toFixed(numOfFloats);
    } else {
        return Math.floor(num);
    }
}

jsfiddle:http://jsfiddle.net/56Lk4/

Upvotes: 1

tabalin
tabalin

Reputation: 2313

Try this one:

function f(number, N) { 
    var intPart = number.toFixed(0),
        decPartLen = N - intPart.length;
    return decPartLen > 0 ? number.toFixed(decPartLen) : intPart;
}

The only difference is that the number will be rounded. But it seems more correct.

Upvotes: 1

Niels
Niels

Reputation: 49919

You can do this:

function x(s, n){
    s = s.toString();
    var sp = s.split(".");
    if( sp[0].length >= n || sp.length == 1  ) return parseFloat(sp[0]);
    return parseFloat( sp[0] + "." + sp[1].substring(0, n - sp[0].length) );
}

console.log(x(2342342.23, 4))// Output 2342342
console.log(x(2342342.23, 8))// Output 2342342.2
console.log(x(2342342.23, 9)) // Output 2342342.23
console.log(x(2342342.23, 15)) // Output 2342342.23

Upvotes: 1

Related Questions