Rounding to nearest 100


I am trying to create a quick calculator embeded in HTML site to calculate nearest 100. I assume 0.1 is 10 and 1 is 100. Try to just create a simplified version similar to this: Can’t get this spit out hudredth.

if(rto=="-1"){var digitcheck = rnumber % 1;
if(digitcheck>"-5"){var newwholenumber = rnumber - digitcheck;}
else{var addnumber = +digitcheck + 1; var newwholenumber = rnumber - addnumber;}
var result = newwholenumber;}

hi @java5747213923 ,

you may want to look into value type that you’re comparing inside the quoted syntax line.

1 Like

Rounding in JavaScript may be different than in other languages. First off, JS, or ES6+ has only one numeric data type… 'number' whose constructor object is Number. That means that the only representation available is floating point. All other representations are by our own inducements on the data.

Furthermore, Math.round() only rounds to the nearest integer, and we can be sure there are some cool mechanics going on in the background for that operation given there is no integer type in the language. Just getting rid of the decimal is problem enough.

x = 1089

Sadly, this simple integer is not stored this way, but as a float. Being an object means it has properties, one of which describes its initial form (one assumes, else how else would we be able to poll it and get the same value?). Object properties is how JS is able to work with data types. There is a lot under the hood.

Now, we want to round to the nearest hundred, which on visual inspection we know will be, 1100. Let’s see how we might arrive at that.

y = Math.round(x / 100) * 100

By dividing, we get to the digit that can be rounded, and round it. Then multiply to take away the initial effect and voila!

10.89 rounds up to 11. 11 * 100 === 1100


As we can see from the above, rounding changes an exact or nearly exact number to a close approximation. We would not trust any math that builds itself upon approximations unless we can expect all values to converge at some point making their difference meaningless. Trouble is in many cases values diverge which contaminates data and makes it meaningless and useless.

Bottom line, store raw data, not rounded approximations. Only use rounding to represent final values, and use reasonable criteria to dictate the level of precision (which is another major area of concern, namely, SIGDIGs).

1 Like