use modulo "%" to round a number to nearest 1000 for example salary ( 543211) to (54300)



  • I have used the

    #include <cmath>
    

    library a function round to give me round value
    for example:

    float Employee::getroundUpSalary() const { 
            return (salary % 1000) * 1000;     
    }                                          
    

    if salary is 543511 it gives me 543000

    I have tried using the below code

    float Employee::getroundUpSalary() const {  
            return round(salary / 1000) * 1000; 
    }                                           
    

    but I get 511000 ( same salary = 543511 figure used as in the above example)

    Is there a way to use modulos (%) to round the salary figure to the nearest 1000?

    Cheers


  • Mod

    How would the remainder help you when rounding? The remainder is like exactly the part that you want to get rid of. I guess you could subtract it from the dividend and go on from there, but then again you could just use regular division to get that same result easier without using modulo. You could change your first code to something like int((salary + 500) / 1000) * 1000 if you do not want to use round from cmath.

    As for your second code: I doubt your results. Computers do not make errors like that. See https://ideone.com/NS8deu . Something in your surrounding program does not do what you think it does.

    if salary is 543511 it gives me 543000
    ...
    but I get 511000

    Just no. 511000 is the result for your first code. It is just a coincidence that it is somewhat close to 543000. The first code is just plain wrong. You are confused about which version of your code you were testing.

    Also in general: salary sounds like it is supposed to be a monetary value. Is that a float (or double) in your program? It looks like it is. That is the wrong data type for money. Money exists in discrete quanti. Floating point data types aim to model continuous spectra but have trouble with discrete numbers. For example, the number 0.10 does not exist as a floating point number. It will acutally be something like 0.1000000015…. Which would be quite fatal if you were to give someone a million dimes. A better data model would be integer data types, using cents (or parts of a cent) as base.



  • It's not that the remainder is useless. If you want to round to the nearest 1000, you can do it with the remainder, but this only works, if you don't want to round to anything else.

        int salary = 1234467;
        int remainder = salary % 1000;
        salary  -= remainder;
        if ( remainder >= 500 )
            salary += 1000;
    

    I'd not recommend that type of solution because its very static and unflexible, but it is possible.


Anmelden zum Antworten