Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I round manually?

I'd like to round manually without the round()-Method. So I can tell my program that's my number, on this point i want you to round. Let me give you some examples:
Input number: 144
Input rounding: 2
Output rounded number: 140

Input number: 123456
Input rounding: 3
Output rounded number: 123500

And as a litte addon maybe to round behind the comma: Input number: 123.456
Input rounding: -1
Output rounded number: 123.460

I don't know how to start programming that... Has anyone a clue how I can get started with that problem?

Thanks for helping me :)

I'd like to learn better programming, so i don't want to use the round and make my own one, so i can understand it a better way :)

like image 664
MikroByte Avatar asked Oct 04 '22 04:10

MikroByte


2 Answers

A simple way to do it is:

  1. Divide the number by a power of ten
  2. Round it by any desired method
  3. Multiply the result by the same power of ten in step 1

Let me show you an example:

You want to round the number 1234.567 to two decimal positions (the desired result is 1234.57).

x = 1234.567;
p = 2;
x = x * pow(10, p);  // x = 123456.7
x = floor(x + 0.5);  // x = floor(123456.7 + 0.5) = floor(123457.2) = 123457
x = x / pow(10,p);   // x = 1234.57
return x;

Of course you can compact all these steps in one. I made it step-by-step to show you how it works. In a compact java form it would be something like:

public double roundItTheHardWay(double x, int p) {
    return ((double) Math.floor(x * pow(10,p) + 0.5)) / pow(10,p);
}

As for the integer positions, you can easily check that this also works (with p < 0).

Hope this helps

like image 94
Barranka Avatar answered Oct 10 '22 12:10

Barranka


if you need some advice how to start,

  • step by step write down calculations what you need to do to get from 144,2 --> 140
  • replace your math with java commands, that should be easy, but if you have problem, just look here and here
like image 29
user902383 Avatar answered Oct 10 '22 13:10

user902383