3 Replies - 611 Views - Last Post: 14 October 2014 - 08:52 AM

#1 Oppemaj  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 23
  • View blog
  • Posts: 94
  • Joined: 15-November 13

Display decimals without rounding

Posted 13 June 2014 - 03:11 PM

An OP posted a thread asking how he could get rid of all decimals and keep just the first decimal digit without rounding down or up.
Finally, he used substring...

See:
http://www.dreaminco...from-substring/

The solution I want to share with you is fairly simple. I'll break it into steps:

1 Multiply the number by 10 (to keep one decimal digit)
2 Drop the rest of decimals.
3 Divide by 10.

Note: This can be done to display any number of decimals(two decimals, three,...)

Option Explicit On
Option Strict On
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim number As Double = 35.735
        'Display the number with one decimal digit without rounding.
        number = CDbl(Fix(number * 10) / 10)
        'The output is 35.7
    End Sub
End Class


Is This A Good Question/Topic? 0
  • +

Replies To: Display decimals without rounding

#2 Oppemaj  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 23
  • View blog
  • Posts: 94
  • Joined: 15-November 13

Re: Display decimals without rounding

Posted 14 October 2014 - 03:24 AM

Removed

This post has been edited by Oppemaj: 14 October 2014 - 03:27 AM

Was This Post Helpful? 0
  • +
  • -

#3 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2270
  • View blog
  • Posts: 9,496
  • Joined: 29-May 08

Re: Display decimals without rounding

Posted 14 October 2014 - 08:29 AM

Also the user could investigate the formatting string available .ToString
Dim s = number.ToString("N2")


Was This Post Helpful? 0
  • +
  • -

#4 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3724
  • View blog
  • Posts: 12,997
  • Joined: 12-December 12

Re: Display decimals without rounding

Posted 14 October 2014 - 08:52 AM

ToString performs rounding, so 35.775 is 35.78 using "N2".



Just to note that in this expression
number = CDbl(Fix(number * 10) / 10)

the CDbl is unnecessary because Fix(double) returns a double and VB's '/' doesn't perform integer division.

This post has been edited by andrewsw: 14 October 2014 - 08:55 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1