数値を0.5に四捨五入する方法を教えてもらえますか?
画面解像度に従ってWebページの要素をスケーリングする必要があります。そのため、フォントサイズをptsで1、1.5または2以降にのみ割り当てることができます。
四捨五入すると、小数点以下1桁に丸めるか、小数点以下なしに丸めます。どうすればこの仕事を達成できますか?
回答:
2で乗算して丸め、次に2で除算する独自の関数を記述します。
function roundHalf(num) {
return Math.round(num*2)/2;
}
roundHalf(15.27)15.5
ここにあなたに役立つかもしれないより一般的な解決策があります:
function round(value, step) {
step || (step = 1.0);
var inv = 1.0 / step;
return Math.round(value * inv) / inv;
}
round(2.74, 0.1) = 2.7
round(2.74, 0.25) = 2.75
round(2.74, 0.5) = 2.5
round(2.74, 1.0) = 3.0
inv意味ですか?inv変数は何を表していますか?
inverseます。
Math.round(-0.5)0を返しますが、数学の規則によれば-1でなければなりません。
詳細:Math.round() およびNumber.prototype.toFixed()
function round(number) {
var value = (number * 2).toFixed() / 2;
return value;
}
round、負の数の点で正の整数のスペクトルに向かう、指定された値より大きい次の整数に丸めます。-2.5は-2になります。あれは正しいですか?
Math.ceil(-1.75) == -1とMath.floor(-1.75) == -2。だから、これにより、最大つまずい取得誰のために、同じようにそれを考えるceilリターンよりも大きい数を、floor返し未満の数を。
0.5を超えて丸めるために、newtronによる上位の回答を拡張する
function roundByNum(num, rounder) {
var multiplier = 1/(rounder||0.5);
return Math.round(num*multiplier)/multiplier;
}
console.log(roundByNum(74.67)); //expected output 74.5
console.log(roundByNum(74.67, 0.25)); //expected output 74.75
console.log(roundByNum(74.67, 4)); //expected output 76
function roundToTheHalfDollar(inputValue){
var percentile = Math.round((Math.round(inputValue*Math.pow(10,2))/Math.pow(10,2)-parseFloat(Math.trunc(inputValue)))*100)
var outputValue = (0.5 * (percentile >= 25 ? 1 : 0)) + (0.5 * (percentile >= 75 ? 1 : 0))
return Math.trunc(inputValue) + outputValue
}
トゥナキのより良い反応を見る前にこれを書いた;)
var f = 2.6;
var v = Math.floor(f) + ( Math.round( (f - Math.floor(f)) ) ? 0.5 : 0.0 );