• 0

[VB.NET]Truncate without rounding


Question

So lets say I have a number, 16.95. I want it truncated to one decimal place, but NO ROUNDING. I want 16.9 for the final result.

So far I'm using:

Dim first As Int32 = Math.Floor(tp)
Dim second As Int32 = Int((tp - first) * 10)
Dim TPs As String = first & "." & second

It works for the following example, but not every time. I think only when there's already one decimal place. Another example:

tp = 16.7

first = 16

tp - first = 6.9999885559082 <---- do not understand

TP is a single, if that matters. I'm having a problem getting that one digit in the tenths place.

Link to comment
https://www.neowin.net/forum/topic/643336-vbnettruncate-without-rounding/
Share on other sites

6 answers to this question

Recommended Posts

  • 0

Dim tp As Single = 16.95

'Fix simply truncates the decimal whereas Math.Floor always rounds down
'  (e.g. Math.Floor(-16.95) = -17, but Fix(-16.95) = -16)
Dim first As Int32 = Fix(tp)
Dim second As Int32 = Int((tp - first) * 10)
Dim TPs As String = first &amp; "." &amp; second

tp = 16.95

first = 16

second = Int((16.95 - 16) * 10) = Int((.95) * 10) = Int(9.5) = 9

TPs = 16.9

For the record, it could be floating-point rounding errors. You might try using a Double rather than a Single.

Fix truncates. Int rounds down to the nearest integer less than or equal to itself, same as Math.floor IIRC. Other things like CInt and Round all use Banker's Rounding, which is a bit odd for some people... If you have a fractional part of .5 or less, the result rounds toward the nearest even integer. Otherwise, the result is rounded to the nearest integer.

Examples:

Using CInt on a value in the range -0.5 to 0.5 results in 0.

Using CInt on a value in the range -1.499999... to -0.500...001 or 0.500...001 to 1.499999... results in -1 or 1, depending on the sign.

Using CInt on a value in the range -2.5 to -1.5 or 1.5 to 2.5 results in -2 or 2, depending on the sign.

Using CInt on a value in the range -3.499999... to -2.500...001 or 2.500...001 to 3.499999... results in -3 or 3, depending on the sign.

Simply put, Banker's Rounding relies on that extra minute fractional piece to round to the appropriate integer. This is why I use Fix for everything - I don't have any issues with negative v.s. positive values like I would with Int or Math.floor or Math.ceiling or whatever. I also don't have rounding issues like with Round and CInt. Everything is predictable, in other words. Of course, the built-in Math.Round does a wonderful job of rounding "the normal way" already, so I suppose my reinventing the wheel using Fix is rather pointless. ^_^

Edited by rpgfan
  • 0

Truncate to 1 decimal place, no rounding:

Dim decimalNumber As Double = 16.95
Dim truncatedNumber As Double = Math.Truncate(decimalNumber * 10) / 10

Should work. Math.Truncate() gets the integral part of the number (the bit before the decimal point). Therefore, if you multiply that by 10, then truncate, and then divide after, you'll get the one decimal place without any rounding.

  • 0
  GSDragoon said:
So lets say I have a number, 16.95. I want it truncated to one decimal place, but NO ROUNDING. I want 16.9 for the final result.

tp = 16.7

first = 16

tp - first = 6.9999885559082 <---- do not understand

Single and double precision numbers are inherently approximative. It's very dangerous with such numbers, for instance, to compare 7 with 7 for equality: one could be 6.999999999 and the other 7.00000000001.

If you need exactitude, use integers only. Define a type that holds the number as an integer and a power of 10. But in most cases you should be fine with the built-in floats, doubles and decimals.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • No, you have no idea, if there is a cable.it is prone to that unless it is shielded.
    • Would be cool if the user can drag it around like a widget. Set a boundary so that it cannot go outside the monitor.
    • missing feew things like CPU temp, hopefully they add an option to customize what would i want displayed or not, but as a default and easy msi afterburner alternative its great and it even work on destiny 2
    • Microsoft Visual Studio Professional 2022 for Windows reaches all-time low price by Steven Parker Today's highlighted deal comes via our Neowin Deals store, where you can save 94% on a copy of Microsoft Visual Studio Professional 2022 for Windows. Visual Studio Professional 2022 is a fully featured development environment that developers around the world know and love. Our first 64-bit IDE makes it easier to work with even bigger projects and more complex workloads. Enhance your productivity, write high-quality code, and re-imagine collaboration with an advanced suite of tools and built-in integrations to tackle the most challenging development workflows and deliver innovative apps. Build across languages & platforms Craft cross-platform mobile and desktop apps with .NET MAUI Build responsive Web UIs in C# with Blazor Build, debug, & test .NET and C++ apps in Linux Use hot reload capabilities across .NET and C++ apps Edit running ASP.NET pages in the web designer view Type less, code more with IntelliCode Understand your code context: variable names, functions, & the type of code you’re writing Complete a line or block of code Get a list of next best options, helping you code more rapidly & accurately Gain deep insights into your code with CodeLens Reveal crucial information like recent changes, authors, tests, and commit history Make informed decisions with a comprehensive overview of your codebase Collaborate seamlessly with Live Share's real-time collaboration sessions Speed up your team's edit & debugging cycles with personalized sessions, access controls, and custom editor settings Ensures everyone's code stays consistent Good to Know ONE-TIME PURCHASE INSTALLED ON 1 DEVICE Redemption deadline: redeem your code within 30 days of purchase Access options: desktop & mobile Version: Professional 2022 Supported languages: Visual Studio is available in English, Chinese (Simplified), Chinese (Traditional), Czech, French, German, Italian, Japanese, Korean, Polish, Portuguese (Brazil), Russian, Spanish, & Turkish Updates included Microsoft Visual Studio Professional 2022 for Windows normally costs $499, but this deal can be yours for just $27.97, that's a saving of $471. For full terms, specifications, and license info, click the link below. Use MSO8 when checking out for additional $8 off. Coupon Expires June 29. Get Microsoft Visual Studio Professional 2022 for Windows for just $19.97, or learn more Although priced in U.S. dollars, this deal is available for digital purchase worldwide. We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • My kids each had a Microsoft account that could log into the family computers, but they did not have admin access, and we didn't have a general guest account or anything like that, so it worked pretty well. You are right, with enough technical knowledge, you can find ways around anything. I still remember I was helping my 10-year-old son with something on his computer and noticed that his account had admin rights. I asked how he did it, and he said he found the BitLocker recovery key, decrypted the drive, then booted a Linux USB and edited the security hive. I told him that if he figured all that out on his own that he deserved admin rights :-)
  • Recent Achievements

    • Week One Done
      Helen Shafer earned a badge
      Week One Done
    • First Post
      emptyother earned a badge
      First Post
    • Week One Done
      Crunchy6 earned a badge
      Week One Done
    • One Month Later
      KynanSEIT earned a badge
      One Month Later
    • One Month Later
      gowtham07 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      665
    2. 2
      ATLien_0
      270
    3. 3
      Michael Scrip
      219
    4. 4
      Steven P.
      166
    5. 5
      +FloatingFatMan
      160
  • Tell a friend

    Love Neowin? Tell a friend!