Вы можете просто попробовать этот метод -
let headers = new Headers({'Accept': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http
.get(this.yourSearchUrlHere, options) // the URL which you have defined
.map((res) => {
res.json(); // using return res.json() will throw error
}
.catch(err) => {
console.error('error');
}
Попробуйте метод Math.Round
. Вот как это сделать:
Math.Round(76d / 100d, 0) * 100;
Math.Round(121d / 100d, 0) * 100;
Math.Round(9660d / 100d, 0) * 100;
Просто добавление к принятому ответу @krizzzn ...
Обратите внимание, что следующее возвращается 0:
Math.Round(50d / 100d, 0) * 100;
Рассмотрим используя следующее и вместо этого верните 100:
Math.Round(50d / 100d, 0, MidpointRounding.AwayFromZero) * 100;
В зависимости от того, что вы делаете, использование десятичных знаков может быть лучшим выбором (обратите внимание на m):
Math.Round(50m / 100m, 0, MidpointRounding.AwayFromZero) * 100m;
Если вы хотите только округлить числовые числа вверх (как это делал OP фактически), вы можете прибегнуть к этому решению:
public static class MathExtensions
{
public static int RoundUpTo(this int number, int nearest)
{
if (nearest < 10 || nearest % 10 != 0)
throw new ArgumentOutOfRangeException(nameof(nearest), $"{nameof(nearest)} must be a positive multiple of 10, but you specified {nearest}.");
int modulo = number % nearest;
return modulo == 0 ? number : modulo > 0 ? number + (nearest - modulo) : number - modulo;
}
}
Если вы хотите выполнить с плавающей запятой (или десятичной) округлить, затем прибегнуть к ответам @krizzzn и @Jim Aho.
Я написал простой метод расширения для обобщения такого рода округления некоторое время назад:
public static class MathExtensions
{
public static int Round(this int i, int nearest)
{
if (nearest <= 0 || nearest % 10 != 0)
throw new ArgumentOutOfRangeException("nearest", "Must round to a positive multiple of 10");
return (i + 5 * nearest / 10) / nearest * nearest;
}
}
Он использует целочисленное деление для поиска ближайшего округления.
Пример использования:
int example = 152;
Console.WriteLine(example.Round(100)); // round to the nearest 100
Console.WriteLine(example.Round(10)); // round to the nearest 10
И в вашем примере:
Console.WriteLine(76.Round(100)); // 100
Console.WriteLine(121.Round(100)); // 100
Console.WriteLine(9660.Round(100)); // 9700
Extension Method
, см. msdn.microsoft.com/en-AU/library/bb383977.aspx , они весьма удобны.
– Jason Larke
22 April 2016 в 12:09
Привет, я пишу это расширение, это получает следующую сотню за каждый номер, который вы передаете
/// <summary>
/// this extension gets the next hunfìdred for any number you whant
/// </summary>
/// <param name="i">numeber to rounded</param>
/// <returns>the next hundred number</returns>
/// <remarks>
/// eg.:
/// i = 21 gets 100
/// i = 121 gets 200
/// i = 200 gets 300
/// i = 1211 gets 1300
/// i = -108 gets -200
/// </remarks>
public static int RoundToNextHundred(this int i)
{
return i += (100 * Math.Sign(i) - i % 100);
//use this line below if you want RoundHundred not NEXT
//return i % 100 == byte.MinValue? i : i += (100 * Math.Sign(i) - i % 100);
}
//and for answer at title point use this algoritm
var closeHundred = Math.Round(number / 100D)*100;
//and here the extension method if you prefer
/// <summary>
/// this extension gets the close hundred for any number you whant
/// </summary>
/// <param name="number">number to be rounded</param>
/// <returns>the close hundred number</returns>
/// <remarks>
/// eg.:
/// number = 21 gets 0
/// number = 149 gets 100
/// number = 151 gets 200
/// number = -149 gets -100
/// number = -151 gets -200
/// </remarks>
public static int RoundCloseHundred(this int number)
{
return (int)Math.Round(number / 100D) * 100;
}
value % 100 == 0
, например. когда этот метод вызывается с i = 200, он возвращает 300.
– feO2x
10 August 2017 в 13:04
Попробуйте это выражение:
(n + 50) / 100 * 100
Я знаю, что это старая нить. Я написал новый метод. Надеюсь, это будет полезно для некоторых.
public static double Round(this float value, int precision)
{
if (precision < -4 && precision > 15)
throw new ArgumentOutOfRangeException("precision", "Must be and integer between -4 and 15");
if (precision >= 0) return Math.Round(value, precision);
else
{
precision = (int)Math.Pow(10, Math.Abs(precision));
value = value + (5 * precision / 10);
return Math.Round(value - (value % precision), 0);
}
}
Пример:
float value = F6666.677777;
Console.Write(value.Round(2)) // = 6666.68
Console.Write(value.Round(0)) // = 6667
Console.Write(value.Round(-2)) // = 6700
int num = 9660;
int remainder = num % 100;
Console.WriteLine(remainder < 50 ? num - remainder : num + (100 -remainder));
Примечание: я не тестировал это полностью.
0
. Может быть, вы могли бы использовать перегрузку средней точки – nawfal 31 October 2012 в 10:42Math.Round
усекает значение, поэтомуMath.Round(50d / 100d, 0)
будет 0. Некоторые люди могут ожидать, что оно будет 100. – Jim Aho 5 April 2016 в 08:41Math.Round(decimal d, int decimals, MidpointRounding mode)
:Math.Round(50d / 100d, 0, MidpointRounding.AwayFromZero);
– krizzzn 5 April 2016 в 13:38MidpointRounding
перечисление ( stackoverflow.com/a/36421665/964821 ) – krizzzn 5 April 2016 в 13:41