• 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

    • Last chance to download DearMob iPhone Manager for PC/Mac (worth $79.95) for free by Steven Parker Claim your complimentary copy worth $79.95 for free today, before the offer ends today on June.3. Download a free licensed copy of DearMob iPhone Manager for effortless backup, restore, and flexible data transfer. Manage videos, photos, music, apps, contacts, ebooks, and 17+ other file types without data erasing risks. Easily transfer, manage, and back up your iPhone or iPad data--safely and without data loss. Free up space and clean unwanted files in just a few clicks. Get your free licensed copy for PC or Mac, fully compatible with all iOS and iPadOS devices. Highlights: Lossless Photo Transfer: Move or albums with zero quality loss; convert HEIC to JPG for easy sharing. Batch Video Export: Transfer videos to your PC without compression, freeing up valuable iPhone space. Custom Music & Ringtones: Add music, playlists, or create ringtones from your favorite songs. One-Click Backup & Restore: Protect your data with fast, reliable backups and restores, plus password encryption Comprehensive Data Management: Manage photos, music, videos, messages, apps, contacts, ebooks, and more. Offline Management: Take full control of your data without needing an internet connection. This free offer ends on 6/3/2025—don’t miss out! How to get it Please ensure you read the terms and conditions to claim this offer. Complete and verifiable information is required in order to receive this free offer. If you have previously made use of these free offers, you will not need to re-register. While supplies last! Free download: DearMob iPhone Manager for PC/Mac (worth $79.95) Offered by Digiarty WinXDVD, view other free resources The below offers are also available for free in exchange for your (work) email: DearMob iPhone Manager for PC/Mac ($79.95 Value) FREE – Expires today 6/3 The Cybersecurity Control Playbook ($100 Value) FREE – Expires 6/4 The Embedded Linux Security Handbook ($31.99 Value) FREE – Expires 6/4 Teach Yourself VISUALLY Microsoft 365, 2nd Edition ($20 Value) FREE – Expires 6/4 Winxvideo AI V3.0 Lifetime License for PC ($69.95 Valued) FREE – Expires 6/8 Aiarty Image Enhancer for PC/Mac ($85 Value) FREE – Expires 6/8 Solutions Architect's Handbook, Third Edition ($42.99 Value) FREE – Expires 6/10 AI and Innovation ($21 Value) FREE – Expires 6/11 Macxvideo AI ($39.95 Value) Free for a Limited Time – Expires 6/22 The Ultimate Linux Newbie Guide – Featured Free content Python Notes for Professionals – Featured Free content Learn Linux in 5 Days – Featured Free content Quick Reference Guide for Cybersecurity – Featured Free content
    • Ignoring the ads, Google Play Store actually works and has no issues installing apps.
    • 2TB Samsung 990 EVO Plus SSD drops to a great price again by Fiza Ali The 2TB Samsung 990 EVO Plus SSD is currently available on Amazon, Samsung, and Newegg at a great price, only $0.44 higher than its historic low. So, if you have been wanting to upgrade your storage solution, you may want to check it out (purchase links down below). The SSD features NAND memory, delivering sequential read speeds of up to 7,250MB/s and write speeds of up to 6,300MB/s. For random read (QD32), the 2TB version reaches up to 1,000K IOPS, and for random write (QD32), it achieves up to 1,350K IOPS. Furthermore, it carries a Total Bytes Written (TBW) rating of 1,200. The 990 EVO Plus is equipped with Intelligent TurboWrite 2.0 for enhanced performance with large files. Moreover, the drive features a nickel-coated controller that helps manage heat, reduce power usage, and prevent overheating. The SSD supports both PCIe 4.0 x4 and PCIe 5.0 x2, promising faster data transfer speeds and better performance. Additionally, with Samsung's Magician Software, the SSD keeps its firmware up to date, adds extra security, and allows for continuous drive health monitoring. Finally, the Samsung 990 EVO Plus SSD comes with a five year limited warranty, offering long-term reliability and peace of mind. 2TB Samsung 990 EVO Plus SSD: $129.99 (Amazon US) - $129.99 (Samsung US) - $129.99 (Newegg) This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. You can also check out other SSD deals here. For hard disk drives, you can head over to our HDD deals section to see if anything from there matches your requirements. Make sure you also browse through Amazon US, Amazon UK, and Newegg US to find some other great tech deals. As an Amazon Associate, we earn from qualifying purchases.
  • Recent Achievements

    • Week One Done
      Adam Todd earned a badge
      Week One Done
    • Contributor
      Ed B went up a rank
      Contributor
    • One Month Later
      moporcho earned a badge
      One Month Later
    • One Month Later
      Parotel earned a badge
      One Month Later
    • Reacting Well
      Cryptecks earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      202
    2. 2
      snowy owl
      146
    3. 3
      ATLien_0
      133
    4. 4
      Xenon
      120
    5. 5
      +FloatingFatMan
      109
  • Tell a friend

    Love Neowin? Tell a friend!