开发者

How to get a fraction from a float number?

开发者 https://www.devze.com 2023-02-04 00:00 出处:网络
I have a floating point number: var f = 0.1457; Or: var f = 4.7005 How do I get just the fraction remainder as integer?

I have a floating point number:

var f = 0.1457;

Or:

var f = 4.7005

How do I get just the fraction remainder as integer?

I.e. in the first example I want to get:

var remainder = 1457;

In the second example:

开发者_如何学JAVAvar remainder = 7005;


function frac(f) {
    return f % 1;
}


While this is not what most people will want, but TS asked for fract as integer, here it is:

function fract(n){ return Number(String(n).split('.')[1] || 0); }
fract(1.23) // = 23
fract(123) // = 0
fract(0.0008) // = 8


This will do it (up to the 4 digits that you want, change the multipler (10000) to larger or smaller if you want smaller or larger number):

Math.ceil(((f < 1.0) ? f : (f % Math.floor(f))) * 10000)


parseInt(parseFloat(amount).toString().split('.')[1], 10)


You can subtract the floor of the number, giving you just the fractional part, and then multiply by 10000, i.e.:

var remainder = (f-Math.floor(f))*10000;


I would argue that, assuming we want to display these values to the user, treating these numbers as strings would be the best approach. This gets round the issue of fractional values such as 0.002.

I came accross this issue when trying to display prices with the cents in superscript.

let price = 23.43; // 23.43
let strPrice = price.toFixed(2) + ''; // "23.43"
let integer = strPrice.split(".")[0] // "23"
let fractional = strPrice.split(".")[1] // "43"


This also depends on what you want to do with the remainder (as commenters already asked). For instance, if the base number is 1.03, do you want the returned remainder as 3 or 03 -- I mean, do you want it as a number or as a string (for purposes of displaying it to the user). One example would be article price display, where you don't want to conver 03 to 3 (for instance $1.03) where you want to superscript 03.

Next, the problem is with float precision. Consider this:

var price = 1.03;
var frac = (price - Math.floor(price))*100;
// frac = 3.0000000000000027

So you can "solve" this by slicing the string representation without multiplication (and optional zero-padding) in such cases. At the same time, you avoid floating precision issue. Also demonstrated in this jsfiddle.

This post about floating precision might help as well as this one.


var strNumber = f.toString();
var remainder = strNumber.substr(strNumber.indexOf('.') + 1, 4);
remainder = Number(reminder);


Similar method to Martina's answer with a basic modulo operation but solves some of the issues in the comments by returning the same number of decimal places as passed in.

Modifies a method from an answer to a different question on SO which handles the scientific notation for small floats.

Additionally allows the fractional part to be returned as an integer (ie OP's request).

function sfract(n, toInt) {
    toInt = false || toInt;
    let dec = n.toString().split('e-');
    let places = dec.length > 1
        ? parseInt(dec[1], 10)
        : Math.floor(n) !== n ? dec[0].split('.')[1].length : 0;
    let fract = parseFloat((n%1).toFixed(places));
    return toInt ? fract * Math.pow(10,places) : fract;
};

Tests

function sfract(n, toInt) {
    toInt = false || toInt;
    let dec = n.toString().split('e-');
    let places = dec.length > 1
        ? parseInt(dec[1], 10)
        : Math.floor(n) !== n ? dec[0].split('.')[1].length : 0;
    let fract = parseFloat((n%1).toFixed(places));
    return toInt ? fract * Math.pow(10,places) : fract;
};

console.log(sfract(0.0000005)); // 5e-7
console.log(sfract(0.0000005, true)); // 5
console.log(sfract(4444)); // 0
console.log(sfract(4444, true)); // 0
console.log(sfract(44444.0000005)); // 5e-7
console.log(sfract(44444.00052121, true)); // 52121
console.log(sfract(34.5697)); // 0.5697
console.log(sfract(730.4583333333321, true)); // 4583333333321


@Udara Seneviratne

const findFraction = (num) => {

  return parseInt( // 5.---------------- And finally we parses a "string" type and returns an integer
    
    // 1. We convert our parameter "num" to the "string" type (to work as with an array in the next step)
    // result: "1.012312"
    num.toString() 

    // 2. Here we separating the string as an array using the separator: " . "
    // result: ["1", "012312"]
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
    .split('.')

    // 3. With help a method "Array.splice" we cut the first element of our array
    // result: ["012312"]
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
    .splice(1.1)

    // 4. With help a method "Array.shift" we remove the first element from an array and returns that
    // result: 012312 (But it's still the "string" type)
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
    .shift()       

  )
}

// Try it
console.log("Result is = " + findFraction (1.012312))
// Type of result
console.log("Type of result = " + typeof findFraction (1.012312))
// Some later operation
console.log("Result + some number is = " + findFraction (1.012312) + 555)

0

精彩评论

暂无评论...
验证码 换一张
取 消