Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 611
  • Last Modified:

how do I find the closest number divisible by 10

I need a function where it will give me the closest number divisible by 10.  The input is a decimal so 85.92 is valid and the output would be 90.

so if the input was
81.9 = 80
84.34 = 80
89.11 = 90
91.4 = 90
85.0 = 90 (this wouldn't happen much because the input is a decimal)
0
jackjohnson44
Asked:
jackjohnson44
  • 5
  • 2
2 Solutions
 
Robert SchuttSoftware EngineerCommented:
Try:
y = 10 * Math.Round(x / 10);

Open in new window

0
 
Robert SchuttSoftware EngineerCommented:
A bit more elaborate (and taking types in account):
private void Form1_Load(object sender, EventArgs e) {
    MessageBox.Show(findClosestDivisible((decimal)84.9, 10).ToString());
}

private int findClosestDivisible(decimal x, decimal divisor) {
    return (int)(divisor * Math.Round(x / divisor, MidpointRounding.AwayFromZero));
}

Open in new window

0
 
Monica PSoftware DeveloperCommented:
Try this logic in your code

Divide by 10, then truncate, then multiply by 10.

229 / 10 = 22,90000...
Math.Truncate(22,9) = 22
22 * 10 = 220.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Robert SchuttSoftware EngineerCommented:
@AkilaPalanimuthu: shouldn't 229 be rounded up to 230?
0
 
Monica PSoftware DeveloperCommented:
229 is just input number..

Incase of 229.5 it can be rounded to 230 and then can apply the logic
0
 
Robert SchuttSoftware EngineerCommented:
That's not what I meant. Maybe I read the question wrong but 229 is closer to 230 than to 220.
0
 
John ClaesSenior .Net Consultant & Technical AnalistCommented:
robert_schutt ,  AkilaPalanimuthu:

Combine your comments ;-)

229 / 10 = 22,90000...
Math.Round(22,9) = 23
23 * 10 = 230.
0
 
Robert SchuttSoftware EngineerCommented:
That was actually my first comment but then I found that code-wise it needed some enhancements, hence my second comment. Also just for fun adding the possibility to use another number than 10. The Math.Round documentation explains that by default 4.5 is rounded down to 4, so even though the OP specified it would be rare, I included the 'MidpointRounding.AwayFromZero' argument for what I shamelessly assume to be mathematically 'normal' behaviour.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now