JankinZhang
V2EX  ›  Node.js

求助大佬 js 生成小数点后有一位或两位的随机数

  •  
  •   JankinZhang · May 12, 2020 · 6141 views
    This topic created in 2369 days ago, the information mentioned may be changed or developed.
    如题 比如 1~2 之间生成 1.2 1.12 这类小数点后位数可控的随机数
    random ()生成的随机数小数太多 取整后当字符串处理加点可读性又太差
    求一个好一点的方法 已经 Google 过了 因为是新手 所以没有收获
    希望大佬帮助 感谢感谢
    6 replies  •  2020-05-15 21:55:50 +08:00
    Zenyk
    Zenyk
    May 12, 2020
    1
    const random = (min = 0, max = 1, rest = 0) => {
    return (Math.random() * max + min).toFixed(rest)
    }
    random(1, 3, 2)
    VDimos
    VDimos
    May 12, 2020 via Android
    2
    toFixed 取小数点后 n 位
    faceRollingKB
    faceRollingKB
    May 12, 2020
    3
    function GetRandomNumber(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min;
    }
    function YourMethod(min, max){
    return GetRandomNumber(min*100, max*100)/100
    }
    JankinZhang
    JankinZhang
    OP
    May 15, 2020
    4
    @Zenyk 感谢感谢
    JankinZhang
    JankinZhang
    OP
    May 15, 2020
    5
    @VDimos 谢谢啦
    JankinZhang
    JankinZhang
    OP
    May 15, 2020
    6
    @faceRollingKB 感谢大佬
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   956 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 19:20 · PVG 03:20 · LAX 11:20 · JFK 14:20
    ♥ Do have faith in what you're doing.