Multiplying a number with a fractionHow to round a number to n decimal places in JavaWhat is JavaScript's highest integer value that a number can go to without losing precision?How do I check if a string is a number (float)?Why can't decimal numbers be represented exactly in binary?Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missingFormat number to always show 2 decimal placesDivide a number by 3 without using *, /, +, -, % operatorsMultiply long or BigInteger by double without loss of precisionAndroid/Java - Multiplying by a fraction seems to be different that multiplying with its decimal equivalent?Split fractional and integral parts of a Double

Should I put programming books I wrote a few years ago on my resume?

2019 gold coins to share

Can the removal of a duty-free sales trolley result in a measurable reduction in emissions?

Separate SPI data

Can a human be transformed into a Mind Flayer?

Grep Match and extract

Why can my keyboard only digest 6 keypresses at a time?

Sci-fi novel: ark ship from Earth is sent into space to another planet, one man woken early from cryosleep paints a giant mural

Ordinal analysis and proofs of consistency

Why AM-GM inequality showing different results?

Why is Na5 not played in this line of the French Defense, Advance Variation?

How to avoid typing 'git' at the begining of every git command

Are polynomials with the same roots identical?

Who won a Game of Bar Dice?

Why did Intel abandon unified CPU cache?

Why does this query, missing a FROM clause, not error out?

What STL algorithm can determine if exactly one item in a container satisfies a predicate?

Solving ‘Null geometry…’ error during distance matrix operation?

How to publish items after pipeline is finished?

Can we completely replace inheritance using strategy pattern and dependency injection?

What is the polarity of this barrel plug with a double circle?

Is using 'echo' to display attacker-controlled data on the terminal dangerous?

Do people with slow metabolism tend to gain weight (fat) if they stop exercising?

Why is long-term living in Almost-Earth causing severe health problems?



Multiplying a number with a fraction


How to round a number to n decimal places in JavaWhat is JavaScript's highest integer value that a number can go to without losing precision?How do I check if a string is a number (float)?Why can't decimal numbers be represented exactly in binary?Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missingFormat number to always show 2 decimal placesDivide a number by 3 without using *, /, +, -, % operatorsMultiply long or BigInteger by double without loss of precisionAndroid/Java - Multiplying by a fraction seems to be different that multiplying with its decimal equivalent?Split fractional and integral parts of a Double






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I was writing some converters of units using BigDecimals and I ran across a situation where I had to multiply a number with a fraction - periodic number.



For most cases the precision is good enough, but lets say we have an equation like:



BigDecimal.valueOf(90)
.multiply(BigDecimal.valueOf(10)
.divide(BigDecimal.valueOf(90), 6, RoundingMode.HALF_UP))


Normally this would equal 10, however because of rounding, we will get 9.999999...



Is there an elegant way of implementing this without having an if condition detecting when the fraction can be cut?










share|improve this question
























  • If you want to deal correctly with fractions, you'll need a Fraction class of some kind. Either roll your own, or have a look at what Apache provides.

    – Dawood ibn Kareem
    Mar 24 at 21:10

















2















I was writing some converters of units using BigDecimals and I ran across a situation where I had to multiply a number with a fraction - periodic number.



For most cases the precision is good enough, but lets say we have an equation like:



BigDecimal.valueOf(90)
.multiply(BigDecimal.valueOf(10)
.divide(BigDecimal.valueOf(90), 6, RoundingMode.HALF_UP))


Normally this would equal 10, however because of rounding, we will get 9.999999...



Is there an elegant way of implementing this without having an if condition detecting when the fraction can be cut?










share|improve this question
























  • If you want to deal correctly with fractions, you'll need a Fraction class of some kind. Either roll your own, or have a look at what Apache provides.

    – Dawood ibn Kareem
    Mar 24 at 21:10













2












2








2








I was writing some converters of units using BigDecimals and I ran across a situation where I had to multiply a number with a fraction - periodic number.



For most cases the precision is good enough, but lets say we have an equation like:



BigDecimal.valueOf(90)
.multiply(BigDecimal.valueOf(10)
.divide(BigDecimal.valueOf(90), 6, RoundingMode.HALF_UP))


Normally this would equal 10, however because of rounding, we will get 9.999999...



Is there an elegant way of implementing this without having an if condition detecting when the fraction can be cut?










share|improve this question
















I was writing some converters of units using BigDecimals and I ran across a situation where I had to multiply a number with a fraction - periodic number.



For most cases the precision is good enough, but lets say we have an equation like:



BigDecimal.valueOf(90)
.multiply(BigDecimal.valueOf(10)
.divide(BigDecimal.valueOf(90), 6, RoundingMode.HALF_UP))


Normally this would equal 10, however because of rounding, we will get 9.999999...



Is there an elegant way of implementing this without having an if condition detecting when the fraction can be cut?







java math floating-point division






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 20:23









Andronicus

7,54432035




7,54432035










asked Mar 24 at 20:27









RadovanRadovan

77110




77110












  • If you want to deal correctly with fractions, you'll need a Fraction class of some kind. Either roll your own, or have a look at what Apache provides.

    – Dawood ibn Kareem
    Mar 24 at 21:10

















  • If you want to deal correctly with fractions, you'll need a Fraction class of some kind. Either roll your own, or have a look at what Apache provides.

    – Dawood ibn Kareem
    Mar 24 at 21:10
















If you want to deal correctly with fractions, you'll need a Fraction class of some kind. Either roll your own, or have a look at what Apache provides.

– Dawood ibn Kareem
Mar 24 at 21:10





If you want to deal correctly with fractions, you'll need a Fraction class of some kind. Either roll your own, or have a look at what Apache provides.

– Dawood ibn Kareem
Mar 24 at 21:10












2 Answers
2






active

oldest

votes


















3














The following will work:



BigDecimal.valueOf(90)
.multiply(BigDecimal.valueOf(10))
.divide(BigDecimal.valueOf(90), 6, RoundingMode.HALF_UP)


The difference is that here the operations are chained, which allows for resolving such cases. In your solution the division needs to be calculated (where error occurs) and then multiplication, because it's passed as argument.






share|improve this answer























  • Awesome. Normally I prefer having parenthesis everywhere when it comes to math in code. Just makes reading and reasoning about the order of operations a lot easier. Didn't realize it interferes with precision. Thanks a lot!

    – Radovan
    Mar 25 at 9:38


















1














Do not know if this will be a general case answer for you, but it works in the example given:



bd = BigDecimal.valueOf(90)
.multiply(BigDecimal.valueOf(10))
.divide(BigDecimal.valueOf(90));


Multiply by 10 then divide by 90.



a * x = ax
- --
z z


You will need to include some rounding logic for rational numbers:



bd = BigDecimal.valueOf(1)
.multiply(BigDecimal.valueOf(1))
.divide(BigDecimal.valueOf(3));


Will fail without rounding.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55328244%2fmultiplying-a-number-with-a-fraction%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    The following will work:



    BigDecimal.valueOf(90)
    .multiply(BigDecimal.valueOf(10))
    .divide(BigDecimal.valueOf(90), 6, RoundingMode.HALF_UP)


    The difference is that here the operations are chained, which allows for resolving such cases. In your solution the division needs to be calculated (where error occurs) and then multiplication, because it's passed as argument.






    share|improve this answer























    • Awesome. Normally I prefer having parenthesis everywhere when it comes to math in code. Just makes reading and reasoning about the order of operations a lot easier. Didn't realize it interferes with precision. Thanks a lot!

      – Radovan
      Mar 25 at 9:38















    3














    The following will work:



    BigDecimal.valueOf(90)
    .multiply(BigDecimal.valueOf(10))
    .divide(BigDecimal.valueOf(90), 6, RoundingMode.HALF_UP)


    The difference is that here the operations are chained, which allows for resolving such cases. In your solution the division needs to be calculated (where error occurs) and then multiplication, because it's passed as argument.






    share|improve this answer























    • Awesome. Normally I prefer having parenthesis everywhere when it comes to math in code. Just makes reading and reasoning about the order of operations a lot easier. Didn't realize it interferes with precision. Thanks a lot!

      – Radovan
      Mar 25 at 9:38













    3












    3








    3







    The following will work:



    BigDecimal.valueOf(90)
    .multiply(BigDecimal.valueOf(10))
    .divide(BigDecimal.valueOf(90), 6, RoundingMode.HALF_UP)


    The difference is that here the operations are chained, which allows for resolving such cases. In your solution the division needs to be calculated (where error occurs) and then multiplication, because it's passed as argument.






    share|improve this answer













    The following will work:



    BigDecimal.valueOf(90)
    .multiply(BigDecimal.valueOf(10))
    .divide(BigDecimal.valueOf(90), 6, RoundingMode.HALF_UP)


    The difference is that here the operations are chained, which allows for resolving such cases. In your solution the division needs to be calculated (where error occurs) and then multiplication, because it's passed as argument.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 24 at 20:39









    AndronicusAndronicus

    7,54432035




    7,54432035












    • Awesome. Normally I prefer having parenthesis everywhere when it comes to math in code. Just makes reading and reasoning about the order of operations a lot easier. Didn't realize it interferes with precision. Thanks a lot!

      – Radovan
      Mar 25 at 9:38

















    • Awesome. Normally I prefer having parenthesis everywhere when it comes to math in code. Just makes reading and reasoning about the order of operations a lot easier. Didn't realize it interferes with precision. Thanks a lot!

      – Radovan
      Mar 25 at 9:38
















    Awesome. Normally I prefer having parenthesis everywhere when it comes to math in code. Just makes reading and reasoning about the order of operations a lot easier. Didn't realize it interferes with precision. Thanks a lot!

    – Radovan
    Mar 25 at 9:38





    Awesome. Normally I prefer having parenthesis everywhere when it comes to math in code. Just makes reading and reasoning about the order of operations a lot easier. Didn't realize it interferes with precision. Thanks a lot!

    – Radovan
    Mar 25 at 9:38













    1














    Do not know if this will be a general case answer for you, but it works in the example given:



    bd = BigDecimal.valueOf(90)
    .multiply(BigDecimal.valueOf(10))
    .divide(BigDecimal.valueOf(90));


    Multiply by 10 then divide by 90.



    a * x = ax
    - --
    z z


    You will need to include some rounding logic for rational numbers:



    bd = BigDecimal.valueOf(1)
    .multiply(BigDecimal.valueOf(1))
    .divide(BigDecimal.valueOf(3));


    Will fail without rounding.






    share|improve this answer



























      1














      Do not know if this will be a general case answer for you, but it works in the example given:



      bd = BigDecimal.valueOf(90)
      .multiply(BigDecimal.valueOf(10))
      .divide(BigDecimal.valueOf(90));


      Multiply by 10 then divide by 90.



      a * x = ax
      - --
      z z


      You will need to include some rounding logic for rational numbers:



      bd = BigDecimal.valueOf(1)
      .multiply(BigDecimal.valueOf(1))
      .divide(BigDecimal.valueOf(3));


      Will fail without rounding.






      share|improve this answer

























        1












        1








        1







        Do not know if this will be a general case answer for you, but it works in the example given:



        bd = BigDecimal.valueOf(90)
        .multiply(BigDecimal.valueOf(10))
        .divide(BigDecimal.valueOf(90));


        Multiply by 10 then divide by 90.



        a * x = ax
        - --
        z z


        You will need to include some rounding logic for rational numbers:



        bd = BigDecimal.valueOf(1)
        .multiply(BigDecimal.valueOf(1))
        .divide(BigDecimal.valueOf(3));


        Will fail without rounding.






        share|improve this answer













        Do not know if this will be a general case answer for you, but it works in the example given:



        bd = BigDecimal.valueOf(90)
        .multiply(BigDecimal.valueOf(10))
        .divide(BigDecimal.valueOf(90));


        Multiply by 10 then divide by 90.



        a * x = ax
        - --
        z z


        You will need to include some rounding logic for rational numbers:



        bd = BigDecimal.valueOf(1)
        .multiply(BigDecimal.valueOf(1))
        .divide(BigDecimal.valueOf(3));


        Will fail without rounding.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 24 at 20:31









        Not a JDNot a JD

        1,367112




        1,367112



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55328244%2fmultiplying-a-number-with-a-fraction%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript