Javascript function to generate similar numbers

Given a floating point number, help me write a function that generates a number with a modified hundredth decimal point.

For instance:

4.32 => 4.38 5.10 => 5.11 8.37 => 8.31 

Below is NOT

 4.32 => 4.29 9.99 => 10.00 
+4
source share
6 answers

Try the following:

 function simNumber(num) { return Math.floor((Math.floor(num * 10) + Math.random()) * 10) / 100; } 
+3
source

Updated:

http://jsfiddle.net/RHy5d/1/

 var num = 3.21; var newNum = (Math.floor(num*10) + Math.random())/10; var newNumRounded = Math.floor(newNum*100)/100; 
+2
source
 function similar(num) { var result = num; while (result == num) { result = parseFloat( num.toFixed(2).substring(0,3) + Math.random().toString().substr(2,1) ); } return result; } 

JSFiddle: http://jsfiddle.net/n3dst4/8KLFa/

+2
source

This function replaces the digit in hundredths with a random digit [0.9], and then performs a reject if it selected the same number. Should work fine:

 function randomHundredths(x) { var r, y; do { r = Math.floor(Math.random() * 10); // [0, 9] y = Number(x.toFixed(2).replace(/\d$/, r)); } while (y == x); return y; } 
+1
source

It works:

 function simNumber(num) { return parseFloat(num.toString() + Math.random().toString().substr(2,1)); } 

Demo: http://jsfiddle.net/2QNqw/

0
source

That should do the trick

 function simNumber(num){ return Math.floor(num) + Math.random() } 

However, it is worth noting that a random function does not necessarily return a value of two decimal places.

Refinement: Math.random () return> 0 and <1

-1
source

Source: https://habr.com/ru/post/1384219/


All Articles