How to round a number to a multiple of 8 in C#

2 Answers

0 votes
using System;

public class Program
{
	private static int roundToMultipleOf(int number, int roundTo) {
		return (number + (roundTo - 1)) & ~(roundTo - 1);
	}

	public static void Main(string[] args)
	{
		Console.WriteLine(roundToMultipleOf(9, 8));
		Console.WriteLine(roundToMultipleOf(19, 8));
		Console.WriteLine(roundToMultipleOf(71, 8));
	}
}

 
 
 
/*
run:
    
16
24
72
    
*/

 



answered Jun 8, 2024 by avibootz
0 votes
using System;

public class Program
{
	public static double roundToMultipleOf(double number, double multipleOf) {
		return multipleOf * (long)Math.Round(number / multipleOf, MidpointRounding.AwayFromZero);
	}

	public static void Main(string[] args)
	{
		Console.WriteLine(roundToMultipleOf(9, 8));
		Console.WriteLine(roundToMultipleOf(19, 8));
		Console.WriteLine(roundToMultipleOf(71, 8));
	}
}

 
 
 
/*
run:
    
8
16
72
    
*/

 



answered Jun 8, 2024 by avibootz

Related questions

2 answers 128 views
2 answers 137 views
2 answers 122 views
1 answer 130 views
2 answers 165 views
2 answers 124 views
2 answers 105 views
...